Cross-platform Communication middleware Thrift Learning "Java version"

Source: Internet
Author: User

Transferred from: Http://neoremind.com/2012/03/%E8%B7%A8%E5%B9%B3%E5%8F%B0%E9%80%9A%E4%BF%A1%E4%B8%AD%E9%97%B4%E4%BB%B6thrift %e5%ad%a6%e4%b9%a0%e3%80%90java%e7%89%88%e6%9c%ac%e3%80%91/

1. What is thrift? Thrift is a cross-language service deployment framework that was originally developed by Facebook in 2007 and entered the Apache Open source project in 2008. Thrift can be used as a binary high-performance communication middleware in cross-platform communication, supporting data (object) serialization and various types of RPC services.  2. What did thrift do for us? First of all, we need to understand that any RPC solution includes the following layers of implementations: • Service Tiers (Services): RPC interface definition and implementation · Protocol layer (Protocol): RPC message format and data encoding format · Transport Layer (transport): implements the underlying communication (such as socket) and system-related functions (such as event looping, multithreading)  thrift the interface and data type of RPC through an intermediate language (IDL, Interface Definition language), Then generate code in different languages via a compiler (currently supports C++,java, Python, PHP, Ruby, Erlang, Perl, haskell, C #, Cocoa, Smalltalk, etc.), And the generated code is responsible for the RPC protocol layer and the Transport layer implementation. We just need to implement the specific interface implementation.  thrift is actually a C/s mode that implements the request response, which generates the server-side code of the interface definition file through the Code generation tool, enabling cross-language support for both the service side and the client. Users declare their services in the Thirft profile, which are compiled to generate code files for the appropriate language, and then the user implements the service.  3. Thrift basic Concept data types      * base Types: Basic types      * struct: struct type      * Container: Container type, list, Set, map     * Exception: Exception type      * Service: Defines an interface for an object, and a series of methods   Protocol layer Type Thrift allows you to select the type of communication protocol that is transmitted between the client and the server, which is generally divided into text and binary (binary) transport protocols on the transport protocol, to conserve bandwidth and provide transmission efficiency, typically   The transport protocol using binary type is the majority, but sometimes the text type-based protocol is used, depending on the actual requirements in the project/product:     * tbinaryprotocol– binary encoded format for data transfer.     * tcompactprotocol– This protocol is very effective and compresses the data using Variable-length Quantity (VLQ) encoding.     * tjsonprotocol– data transmission using JSON encoding protocol.     * tsimplejsonprotocol– This savings only provides JSON-only protocols for parsing by scripting language     * tdebugprotocol– helping developers debug during development, It is easy to read in the form of text.   Transport Layer Type     * tsocket– is the most common mode of transmission using clogged I/O.     * thttptransport– uses the HTTP transport protocol for data transfer     * tfiletransport– as the name implies in the process of file transfer, although this way does not provide Java implementation, But the implementation is very simple.     * tzlibtransport– uses perform zlib compression and does not provide Java implementations.      The following categories are mainly decorated with the above categories (using decorative mode) to improve transmission efficiency.     tbufferedtransport– The data for a transport object operation, that is, reading data from buffer, or writing data directly to buffer    tframedtransport– is used in a non-blocking service with frame as a unit of transmission. Similar to Tbufferedtransport, buffer is also available for the relevant data, and it supports fixed-length data sending and receiving.     tmemorybuffer– Read and write data from a buffer, using memory I/O is like the Bytearrayoutputstream implementation in Java.   Server type     * tsimpleserver– simple single-threaded service model, commonly used for testing     * tthreadedserver– multithreaded service models, usingBlocking IO, each request creates a thread.     * tthreadpoolserver– thread pool service model, using standard blocking IO, to pre-create a set of thread processing requests.     * tnonblockingserver– multithreaded service model, using non-blocking IO (using Tframedtransport data transfer method)  4. The Thrift schema Thrift contains a complete stack structure for building the client and server side. Depicts the overall architecture of the thrift.    The yellow part of the figure is the user-implemented business logic, the brown part is the client and server-side code framework generated from the service interface profile defined by Thrift, and the red part is the read-write operation of the data based on the Thrift file generation code. Red section below is the Thrift transport system, protocol, and underlying I/O communication, using Thrift to easily define a service and choose a different transport protocol and transport layer without having to regenerate the code. The  thrift server contains the infrastructure for binding protocols and transport layers, which provides blocking, non-blocking, single-threaded, and multithreaded modes to run on the server and can be run with the server/container, and can be seamlessly combined with the existing Java EE Server/web container.  5. Install http://thrift.apache.org/  official website download, need to use ant to compile into Lib, the final actual project only need to add the following jar package: * libthrift.jar* slf4j-api-1.5.8.jar* slf4j-log4j12-1.5.8.jar* log4j-1.2.15.jar 6. A simple instance creates a simple HelloWorld. First write the script file according to the Thrift Syntax specification Hello.thrift, the code is as follows: 
namespace Java Service.demo  service hello{   string hellostring (1:string para)   i32 helloint (1:i32 para)   bool Helloboolean (1:bool para)   void hellovoid ()   string Hellonull ()  }
There are five methods that define the service Hello, each containing a method name, a parameter list, and a return type. Each parameter consists of a parameter ordinal, a parameter type, and an argument name. Using Thrift.exe-gen Java hello.thrift to generate two Gen-java folders, there is a server-side interface that we generated Hello.java. Create the Helloserviceimpl.java file and implement the Hello.iface interface in the Hello.java file, with the following code:
Package Service.demo;  Import org.apache.thrift.TException;  public class Helloserviceimpl implements Hello.iface {     @Override public     Boolean Helloboolean (Boolean para) Throws Texception {         return para;     }     @Override public     int helloint (int para) throws texception {         try {             thread.sleep (20000);         } catch ( Interruptedexception e) {             e.printstacktrace ();         }         return para;     }     @Override public     String Hellonull () throws texception {         return null;     }     @Override public     string hellostring (string para) throws texception {         return para;     }     @Override public     void Hellovoid () throws Texception {         System.out.println (" Hello world");     }  }
Create a server-side implementation code that passes Helloserviceimpl as a specific processor to the Thrift server with the following code:

  Package service.server;  Import Org.apache.thrift.TProcessor;  Import Org.apache.thrift.protocol.TBinaryProtocol;  Import Org.apache.thrift.protocol.TBinaryProtocol.Factory;  Import Org.apache.thrift.server.TServer;  Import Org.apache.thrift.server.TThreadPoolServer;  Import Org.apache.thrift.transport.TServerSocket;  Import org.apache.thrift.transport.TTransportException;  Import Service.demo.Hello; Import Service.demo.HelloServiceImpl;   public class Helloserviceserver {/** * start Thrift Server * @param args */public static void Mai N (string[] args) {try {//Set service port to 7911 tserversocket servertransport = new Tserversocket             (7911);             Set the Protocol factory to tbinaryprotocol.factory Factory profactory = new Tbinaryprotocol.factory ();             The implementation of the associated processor and the Hello service Tprocessor processor = new Hello.processor (new Helloserviceimpl ()); Tserver Server = new Tthreadpoolserver (processor, SERVERTRANSPORT, profactory); System.out.println ("             Start server on port 7911...");         Server.serve ();         } catch (Ttransportexception e) {e.printstacktrace (); }     }  }
Create the client implementation code, call Hello.client to access the service side of the logical implementation, the code is as follows: 
Package service.client;  Import org.apache.thrift.TException;  Import Org.apache.thrift.protocol.TBinaryProtocol;  Import Org.apache.thrift.protocol.TProtocol;  Import Org.apache.thrift.transport.TSocket;  Import Org.apache.thrift.transport.TTransport;  Import org.apache.thrift.transport.TTransportException; Import Service.demo.Hello;   public class Helloserviceclient {/** * call Hello Service * @param args */public static void main (STR Ing[] Args {try {//Set call service address local, port 7911 ttransport transport = new Tsocket ("             Localhost", 7911);             Transport.open ();             Set the transport protocol to tbinaryprotocol Tprotocol protocol = new Tbinaryprotocol (transport);             Hello.client Client = new hello.client (protocol);             Call the Hellovoid method of the service client.hellovoid ();         Transport.close ();         } catch (Ttransportexception e) {e.printstacktrace (); } catch (Texception e) {e.printstacktrace (); }     }  }
 After the code is written to run the server, and then start the client Invoke service Hello method hellovoid, the server-side console window output "Hello world".

Cross-platform Communication middleware Thrift Learning "Java version" (RPM)

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.