Apache Thrift series explain (a) - Overview and Getting Started

Introduction
Thrift is a lightweight, remote service invocation framework for cross-language, originally developed by Facebook, back to the Apache open source project. It is through its own IDL intermediate language, and with the code generation engine to generate a variety of mainstream languages RPC server / client template code.

Thrift support many different programming languages, including C ++, Java, Python, PHP, Ruby, etc., the series focuses on the Java language Thrift configuration and specific use.

Text
Thrift technology stack
Thrift defined software stack is very clear, so that the various components can be loosely coupled, for different application scenarios, is the way to select a different build a service.

 

Thrift layered software stack from bottom to top are: the transport layer (Transport Layer), Layer protocol (Protocol Layer), the treatment layer (Processor Layer) and Layer Service (Server Layer).

Transport Layer (Transport Layer): the transport layer is responsible for reading and writing data directly from the network, which defines the specific network transport protocol; example TCP / IP transmission.

Protocol layer (Protocol Layer): Layer protocol defines the format of data transmission, responsible for the serialization and deserialization of data transmission network; example JSON, XML, binary data.

Treatment layer (Processor Layer): treatment layer is generated by the IDL specific (Interface Description Language), and encapsulates the underlying network specific serialization and transmission, and to delegate the user to achieve Handler processed.

Service layer (Server Layer): the integration of the above components, provides network specific thread / IO service model, the final service.

Thrift characteristics of
(a) development speed
by writing RPC interface Thrift the IDL file, the server automatically generates skeleton (Skeletons) and client stubs (Stubs) using a compiler generator. Thereby eliminating the need for developers to customize, and maintain codec interfaces, messaging, multi-threaded server model and other basic work.

Server: only need to follow the service interfaces skeleton that is, write a good business deal with the specific program (Handler), ie implementation class can be.
Client: just copy the IDL definition of good customer service targets and end pile, then just call the local object's method calls as remote servers.
(B) the interface simple maintenance
by the maintenance Thrift IDL format (Interface Description Language) files (Note written comments), can be used as an interface to the Client for use document, automatically generate interface code, and always maintain the consistency of code and documentation . Thrift protocol support and flexible scalability interface.

(C) learning costs low
because it comes from Google Protobuf development team, so its style is similar to Google Protobuf IDL files, and more readable and understandable; in particular, RPC-style service interface is like writing an object-oriented Class as simple.

Beginners only reference: http: //thrift.apache.org/, more than an hour you can understand the syntax of using the Thrift IDL file.

(Iv) multi-lingual / cross-language support
Thrift supports C ++, Java, Python, PHP , Ruby, Erlang, Perl, Haskell, C #, Cocoa, JavaScript, Node.js, Smalltalk and other languages, you can generate above-language server and the client program.

We often use for Java, PHP, Python, C ++ support is good, although iOS environment Objective-C (Cocoa) support slightly inferior, but also to fully meet our requirements.

(E) Stable / widely used
Thrift in many open source projects have been verified to be stable and efficient, such as Cassandra, Hadoop, HBase and so on; abroad are widely used in Facebook, the country, including Baidu, the US group millet, and hungry yet and other companies.

 

Thrift data types
Thrift script definable data types include the following types:

Basic Type:
  BOOL: Boolean
  byte: 8-bit signed integer
  i16: 16-bit signed integer
  i32: 32-bit signed integer
  i64: 64-bit signed integer
  double: 64-bit floating point
  string encoded in UTF-8: string
  binary: the binary string of
the type of structure:
  struct: Object structure defined
type of container:
  list: an ordered list of elements
  set: no repeat unordered collection of elements
  map: ordered key / value set
exception types:
  exception: exception type
service type :
  -service: the corresponding service class specific
Thrift protocol
Thrift allows users to select a category transmission communication protocol between client and server, a transport protocol generally divided text (text) and binary (binary) transmission protocol. To save bandwidth and improve transmission efficiency, using binary transport protocol for most types Under normal circumstances, sometimes using text-based type of agreement, which requires the actual needs of the project / product based. Common protocols are the following:

TBinaryProtocol: binary encoding format for data transmission
TCompactProtocol: high efficiency, dense binary encoding format for data transmission
TJSONProtocol: the use of data encoding protocol JSON text data transmission
TSimpleJSONProtocol: only provide protocol JSON write only for scripting language parsing
Thrift transport layer
common transport layer are the following:

TSocket: blocking the use of I / O transmission, is the most common mode
TNonblockingTransport: nonblocking way for building asynchronous client
TFramedTransport: nonblocking way for transmission by the size of the block, similar to Java in the NIO
the Thrift the server type
TSimpleServer: single-threaded server, using standard blocking the I / O
TThreadPoolServer: multi-threaded server, using standard blocking the I / O
TNonblockingServer: single-threaded server-side, non-blocking use of the I / O
THsHaServer: semisynchronous half asynchronous server-side processing based non-blocking IO to read and write and multi-threaded tasks
TThreadedSelectorServer: multi-threaded server-side selector for THsHaServer enhanced asynchronous IO on the model
Thrift start example
(a) preparation of Thrift IDL files
a) Download 0.10.0 of Thrift IDL compiler, download address: http: //thrift.apache.org/docs/install. .Java interface generated by the compiler generates class files.

 

b). .exe file downloaded Windows installation environment, will join thrift.exe path environment variable. Installation Thrift editing plug-in on Idea.

 

. C) write hello.thrift IDL file:

the HelloWorldService {-Service
String say (. 1: String username)
}

. D) using the generated code code generation tool, run the following command:

-gen Java hello.thrift Thrift
. 1
E). Since the target directory is not specified code generation, the generated class files stored in the default directory gen-java. Here HelloWorldService.java generate a class file, the file size exceeds thousands of rows, following the interception of part of the core code.

public class HelloWorldService {
public interface Iface {
public String say(String username) throws org.apache.thrift.TException;
}

public interface AsyncIface {
public void say(String username, org.apache.thrift.async.AsyncMethodCallback<String> resultHandler) throws org.apache.thrift.TException;
}

public static class Client extends org.apache.thrift.TServiceClient implements Iface {
public static class Factory implements org.apache.thrift.TServiceClientFactory<Client> {
public Factory() {
}

public Client getClient(org.apache.thrift.protocol.TProtocol prot) {
return new Client(prot);
}

public Client getClient(org.apache.thrift.protocol.TProtocol iprot, org.apache.thrift.protocol.TProtocol oprot) {
return new Client(iprot, oprot);
}
}

public Client(org.apache.thrift.protocol.TProtocol prot) {
super(prot, prot);
}

public Client(org.apache.thrift.protocol.TProtocol iprot, org.apache.thrift.protocol.TProtocol oprot) {
super(iprot, oprot);
}

public String say(String username) throws org.apache.thrift.TException {
send_say(username);
return recv_say();
}
// 省略.....
}

public static class AsyncClient extends org.apache.thrift.async.TAsyncClient implements AsyncIface {
public static class Factory implements org.apache.thrift.async.TAsyncClientFactory<AsyncClient> {
private org.apache.thrift.async.TAsyncClientManager clientManager;
private org.apache.thrift.protocol.TProtocolFactory protocolFactory;

public Factory(org.apache.thrift.async.TAsyncClientManager clientManager, org.apache.thrift.protocol.TProtocolFactory protocolFactory) {
this.clientManager = clientManager;
this.protocolFactory = protocolFactory;
}

public AsyncClient getAsyncClient(org.apache.thrift.transport.TNonblockingTransport transport) {
return new AsyncClient(protocolFactory, clientManager, transport);
}
}

public AsyncClient(org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.async.TAsyncClientManager clientManager, org.apache.thrift.transport.TNonblockingTransport transport) {
super(protocolFactory, clientManager, transport);
}

void say public (String username, org.apache.thrift.async.AsyncMethodCallback <String> resultHandler) throws org.apache.thrift.TException {
checkReady ();
say_call method_call An invocation of new new say_call = (username, resultHandler, the this, ___protocolFactory, ___transport) ;
the this .___ = method_call An invocation of currentMethod;
___ manager.call (method_call An invocation of);
}
// omitted .....
}
// omitted .....
}

for developers, the use of native Thrift frame, only need to focus on the following four internal interface core / classes: Iface, AsyncIface, Client and AsyncClient.

Iface: HelloWorldService.Iface server by implementing the interface, to provide specific synchronization business logic end.
AsyncIface: HelloWorldService.Iface server by implementing the interface, to provide specific asynchronous business logic end.
Client: The client in a synchronized manner to access services provided by the method server instance object HelloWorldService.Client of.
AsyncClient: client asynchronously access services provided by the server-side method HelloWorldService.AsyncClient instance of an object.
(B) new Maven project
a). New maven project, dependent on the introduction of thrift, used here is version 0.10.0.

<dependency>
<the groupId> org.apache.thrift </ the groupId>
<the artifactId> libthrift </ the artifactId>
<Version> 0.10.0 </ Version>
</ dependency>

B). The resulting class source file copy HelloWorldService.java source file into the project directory, and implementation-defined HelloWorldService.Iface the say () method.

HelloWorldServiceImpl.java

HelloWorldServiceImpl the implements HelloWorldService.Iface {class public
@Override
public String say (String username) throws TException {
return "the Hello" username +;
}
}

C) to write server-side program:

SimpleServer.java

public class SimpleServer {
public static void main(String[] args) throws Exception {
ServerSocket serverSocket = new ServerSocket(ServerConfig.SERVER_PORT);
TServerSocket serverTransport = new TServerSocket(serverSocket);
HelloWorldService.Processor processor =
new HelloWorldService.Processor<HelloWorldService.Iface>(new HelloWorldServiceImpl());

TBinaryProtocol.Factory protocolFactory = new TBinaryProtocol.Factory();
TSimpleServer.Args tArgs = new TSimpleServer.Args(serverTransport);
tArgs.processor(processor);
tArgs.protocolFactory(protocolFactory);

// simple single-threaded service model is generally used to test
tserver tserver = new new TSimpleServer (tArgs);
System.out.println ( "Running the Simple Server");
; tServer.serve ()
}
}

write d) client program:

SimpleClient.java

public class SimpleClient {
public static void main(String[] args) {
TTransport transport = null;
try {
transport = new TSocket(ServerConfig.SERVER_IP, ServerConfig.SERVER_PORT, ServerConfig.TIMEOUT);
TProtocol protocol = new TBinaryProtocol(transport);
HelloWorldService.Client client = new HelloWorldService.Client(protocol);
transport.open();

Result = client.say String ( "Leo");
System.out.println ( "= the Result:" Result +);
} the catch (TException E) {
e.printStackTrace ();
} the finally {
IF (! = Null Transport) {
transport.close ();
}
}
}
}

. E) run the program server, server side of the connection request in the specified port monitor client console log output start:

 

. F) running the client program, the client via the network requests HelloWorldService say () method of the specific implementation, the console output returns the result:

 

Based on a simple service here used a single-threaded model synchronization, generally used only for entry-learning and testing!

Summary
paper on the concept of Thrift made related presentations, experience a lot thrift how to program!
----------------

Original link: https: //blog.csdn.net/baidu_22254181/article/details/82814489

Guess you like

Origin www.cnblogs.com/sea520/p/12165769.html