Writing programs using thrift RPC (server side and client)

Source: Internet
Author: User

1. Thrift Class Introduction
The Thrift Code package (located at THRIFT-0.6.1/LIB/CPP/SRC) has several directories:

Concurrency: Libraries for concurrency and clock management
Processor:processor Related Classes
Protocal:protocal Related Classes
Transport:transport Related Classes
Server:server Related Classes

1.1 Transport Class (what is transmitted?) )
For data transfer, there are several available classes:
Tfiletransport: File (log) Transport class that allows the client to pass the file to the server, allowing the server to write the received data to a file;
Thttptransport: The use of HTTP transmission protocol for data transmission;
Tsocket: Using TCP socket for data transmission;
Tzlibtransport: After compressing the data to transfer, or extract the data received. The following classes are mainly decorated with the above categories (using decorative mode) to improve transmission efficiency.
Tbufferedtransport: Buffer of data that is manipulated by a transport object, which reads data from buffer, or writes data directly to buffer;
Tframedtransport: Similar to Tbufferedtransport, the relevant data will be buffer, at the same time, it supports the fixed-length data transmission and reception;
Tmemorybuffer: Reads and writes data from a buffer.
1.2 Protocol class (what is transmitted?) )
Responsible for data encoding, there are several classes available:
Tbinaryprotocol: Binary encoding
Tjsonprotocol:json encoding
Tcompactprotocol: Dense binary encoding
Tdebugprotocol: Organize your data in a user-readable way 1.3 Server Class (providing service for clients)
Tsimpleserver: Simple single-threaded server, mainly used for testing
Tthreadpoolserver: Multi-threaded server with standard blocking IO
Tnonblockingserver: A multithreaded server that uses non-blocking IO, tframedtransport must use this type of server
1.5 serialization and deserialization of objectsThe Protocol in thrift is responsible for encoding the data so that it can be serialized and deserialized using protocol related objects. 2. Writing client and server 2.1 Client-side code writing
The methods written by the client are divided into the following steps:
(1) Define the Ttransport, set the transfer mode (such as socket, HTTP, etc.) for your client.
(2) Define protocal, use decorative mode (decorator design mode) to encapsulate Ttransport, set encoding format for your data (such as binary format, JSON format, etc.)
(3) Instantiate the client object and invoke the service interface.
Note: If the user defines a service called ${server_name} in the thrift file, an object called ${server_name}client is generated. 2.2 Server-side code authoring
(1) Define a tprocess, this is a class that thrift automatically generated based on user-defined thrift files
(2) using Tservertransport to obtain a ttransport
(3) with Ttransportfactory, the original transfer is optionally converted to a suitable application transmission (typically using tbufferedtransportfactory)
(4) Use Tprotocolfactory to create an input and output for the Ttransport
(5) Create a Tserver object (single thread, you can use Tsimpleserver, and for multi-threading, the user can use Tthreadpoolserver or tnonblockingserver) to invoke its server () function.
Description: Thrift will generate a simple server code (pile) for each thrift file with service. 3. Example:

1. Thrift Generate Code

Create the Thrift file: G:\test\thrift\demoHello.thrift, which reads as follows:

namespace Java Com.micmiu.thrift.demo service HelloWorldService {string SayHello (1:string username)}
Thrift-0.8.0.exe is a Windows compiler tool available on the website that uses this tool to generate the relevant code: Thrift-0.8.0.exe-r-gen java./demohello.thrift Copy the generated Helloworldservice.java file to your own test project, my project was built with Maven, so add the following in Pom.xml: <dependency>
<groupId>org.apache.thrift</groupId>
<artifactId>libthrift</artifactId>
<version>0.8.0</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.5.8</version>
</dependency>

2. Implement Interface Iface

Java code: Helloworldimpl.java Package Com.micmiu.thrift.demo;
Import org.apache.thrift.TException;

public class Helloworldimpl implements Helloworldservice.iface {
Public Helloworldimpl () {
}
@Override
public string SayHello (string username) throws Texception {
Return "Hi," + username + "Welcome to my blog www.micmiu.com";
}
}

3.TSimpleServer Service Side

Simple single-threaded service model, typically used for testing.

Write server-side code: Helloserverdemo.java Package Com.micmiu.thrift.demo;
Import Org.apache.thrift.TProcessor;
Import Org.apache.thrift.protocol.TBinaryProtocol;
Import Org.apache.thrift.protocol.TCompactProtocol;
Import Org.apache.thrift.protocol.TJSONProtocol;
Import Org.apache.thrift.protocol.TSimpleJSONProtocol;
Import Org.apache.thrift.server.TServer;
Import Org.apache.thrift.server.TSimpleServer;
Import Org.apache.thrift.transport.TServerSocket;

public class Helloserverdemo {
public static final int server_port = 8090;
public void StartServer () {
try {
System.out.println ("HelloWorld tsimpleserver start ...");
Tprocessor tprocessor = new helloworldservice.processor&lt; Helloworldservice.iface&gt; (
New Helloworldimpl ());
helloworldservice.processor&lt; Helloworldservice.iface&gt; Tprocessor =
New helloworldservice.processor&lt; Helloworldservice.iface&gt; (
New Helloworldimpl ());
Simple single-threaded service model, typically used for testing
Tserversocket servertransport = new Tserversocket (server_port);
Tserver.args Targs = new Tserver.args (servertransport);
Targs.processor (Tprocessor);
Targs.protocolfactory (New Tbinaryprotocol.factory ());
Targs.protocolfactory (New Tcompactprotocol.factory ());
Targs.protocolfactory (New Tjsonprotocol.factory ());
Tserver Server = new Tsimpleserver (Targs);
Server.serve ();
} catch (Exception e) {
System.out.println ("Server start error!!!");
E.printstacktrace ();
}
}
/**
* @param args
*/
public static void Main (string[] args) {
Helloserverdemo Server = new Helloserverdemo ();
Server.startserver ();
}
Write client-side code: Helloclientdemo.java Package Com.micmiu.thrift.demo;
Import org.apache.thrift.TException;
Import Org.apache.thrift.protocol.TBinaryProtocol;
Import Org.apache.thrift.protocol.TCompactProtocol;
Import Org.apache.thrift.protocol.TJSONProtocol;
Import Org.apache.thrift.protocol.TProtocol;
Import Org.apache.thrift.transport.TSocket;
Import Org.apache.thrift.transport.TTransport;
Import org.apache.thrift.transport.TTransportException;

public class Helloclientdemo {
public static final String server_ip = "localhost";
public static final int server_port = 8090;
public static final int TIMEOUT = 30000;
/**
*
* @param userName
*/
public void Startclient (String userName) {
Ttransport transport = NULL;
try {
Transport = new Tsocket (server_ip, Server_port, TIMEOUT);
Agreement to be consistent with the service side
Tprotocol protocol = new Tbinaryprotocol (transport);
Tprotocol protocol = new Tcompactprotocol (transport);
Tprotocol protocol = new Tjsonprotocol (transport);
Helloworldservice.client Client = new Helloworldservice.client (
protocol);
Transport.open ();
String result = Client.sayhello (userName);
SYSTEM.OUT.PRINTLN ("thrify Client result =:" + result);
} catch (Ttransportexception e) {
E.printstacktrace ();
} catch (Texception e) {
E.printstacktrace ();
} finally {
if (null! = Transport) {
Transport.close ();
}
}
}
/**
* @param args
*/
public static void Main (string[] args) {
Helloclientdemo client = new Helloclientdemo ();
Client.startclient ("Michael");
}
}

Run the service-side program first, the log is as follows:

HelloWorld tsimpleserver start ....

To run the client-side invoker again, log the following:

Thrify client result =: Hi,michael Welcome to my blog www.micmiu.com

The test was successful, consistent with the expected return information.

Summary: Basic steps for server-side and client-side coding

1. Server-side Coding basic steps:

    • Implement the service Processing interface Impl
    • Create Tprocessor
    • Create Tservertransport
    • Create Tprotocol
    • Create Tserver
    • Start the server

2. Basic client code steps:

    • Create transport
    • Create Tprotocol
    • Create a Client based on Ttransport and Tprotocol
    • The corresponding method of calling the client
References:http://www.micmiu.com/soa/rpc/thrift-sample/
http://dongxicheng.org/search-engine/thrift-rpc/

Writing programs using thrift RPC (server side and client)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.