Microservice Patterns and Best Practices
上QQ阅读APP看书,第一时间看更新

Apache Thrift

Thrift is a project created by Facebook and maintained by the Apache Software Foundation. It has a good level of compatibility with the languages most commonly used in the market of programming.

Thrift has the communication layer with RPC and a part of serialization using a file .thrift as a template. The file .thrift has notation and types similar to the C++ language in which Thrift was developed.

An example of file .thrift can be viewed in the following:

    typedef i32 MyInteger 
 
    const i32 INT32CONSTANT = 9853 
    const map<string,string> MAPCONSTANT = {'hello':'world', 
'goodnight':'moon'} enum Operation { ADD = 1, SUBTRACT = 2, MULTIPLY = 3, DIVIDE = 4 } struct Work { 1: i32 num1 = 0, 2: i32 num2, 3: Operation op, 4: optional string comment, } exception InvalidOperation { 1: i32 whatOp, 2: string why } service Calculator extends shared.SharedService { void ping(), i32 add(1:i32 num1, 2:i32 num2), i32 calculate(1:i32 logid, 2:Work w) throws
(1:InvalidOperation ouch), oneway void zip() }

Do not worry about the file contents. The important thing is realizing the flexibility that is offered by the RPC Thrift composition. An interesting point to note is the following line of code:

    service Calculator extends shared.SharedService { ...  

Thrift allows the use of inheritance among the template files, which will be used by code generators.

To create the client/server using Thrift, simply use the following command line:

   $ thrift -r --gen py file_name.thrift  

The preceding line will create a client and server in the Python programming language.

Among the options presented, the most common at the moment are Thrift and gRPC, and any one of these tools is a good deployment option for direct communication between microservices.