Thrift file writing

Source: Internet
Author: User

1. Data Type of thrift. (This is mainly for translating official documents)

A. Basic Data Types

1) boolean type; Value: true or false

2) byte type, with a single-byte letter Value

3) I16 type, with a 16-bit integer signed number.

4) i32 type, with a 32-bit integer signed number.

5) i64 type, with 64-bit integer signed numbers.

6) Double-type floating point number with a value of 64.

7) string type, string or binary data.

B. struct

A struct similar to C. Those who do not understand C can understand it as classes without methods, but only attributes.

Type:

    

struct Work {1: i32 num1 = 0,2: i32 num2,3: Operation op,4: optional string comment,}

 

C. Container

1) list type.

A set of ordered elements, similar to the arraylist class of Java.

    

typedef i32 MyIntegerMyInteger a;struct hello{    list<MyInteger> d; }

The Hello struct contains a list type of data, and all the elements in it must be myinteger data of the data type. The typedef is used as an alias.

2) Set Type

A set of non-repeated sorting elements, similar to Java's hashset and Python's set. Use the same list

3) Map <type1, type2> type.

Example:

map<string,string> MAPCONSTANT = {'hello':'world', 'goodnight':'moon'}

4) Enumeration type

 

2. Service

With the data structure, you should operate on the data. Thrift's service mentioned here cannot target our own business logic. Instead, it refers to a set of methods for the server to read data from the port and the client to pass data.

Service <service name >{< return type> <Method Name> (parameter) throws <exception>}

3. Practice:

Write the following thrift file named test. Thrift Based on the Data Type and struct mentioned above.

i32 a;i32 b;string c;list<string> d;map<string, string> e = {"hello" : "world", "dd" : "ee"};struct f{    1:a,    2:b,    3:c=2,    4:d="ceshi",    5:e,}service Hello{    f get_f(1:f gg) throws (Exception, e)}

Using the thriftstandard command (thrift.exe-gen py test. Thrift) with the above Code is not successful, because the syntax is still incorrect!

Modify

1. Constant quantities such as A, B, C, D, and E must be modified using Const.

2. if the const modifier is used, but there is a; number, it is still not successful, although some people say thrift is correct; not sensitive, it is estimated that the version is used, here I am using the latest version 0.8. That is to say, if you are a Java or PHP programmer, please note that there is no ";"

3. assign values to static variables, for example, const i32 A = "helloworld"

4. Specify the parameter type for the internal attributes of the struct because the internal attributes of the struct have nothing to do with the external static attributes.

5. No "," is separated between exceptions and is replaced by spaces.

6. Define the exception type.

7. Set the throws parameter to the first parameter.

Okay. The modified thrift script becomes

const i32 a = 1const i32 b = 2const string c = "helloworld"const list<string> d = "test"const map<string, string> e = {"hello" : "world", "dd" : "ee"}struct f{    1:i32 a,    2:i32 b,    3:string c,    4:list<string> d=["ceshi"],    5:map<string,string> e = {"hello":"world"},}exception Exception{    1:i32 what;    2:string where;}service Hello{    f get_f(1:f gg) throws (1:Exception e)}

A little bit like a production environment, the code structure is generated:

We can use this script to complete some functions for us. For example, get_f allows us to calculate the various values of the GG object of the struct F. Of course, the generated environment can also be integrated with the database.

 

Now we need several data communication interfaces.

1. Read data: readmessagebegin ()

(Fname, mtype, rseqid) = self. _ iprot. readmessagebegin ()

Read the request stream from the port and obtain three values.

Readmessageend () ends reading data.

2. readstructbegin () starts to read the struct

Readstructend () ends reading the struct

3. readfieldbegin () starts to read the attribute.

Readfieldend ()

4. readmapbegin () starts to read Map

Readmapend () reads map.

There are many other data interfaces here, which are not listed one by one, because when we use thrift, as long as it is not similar to modifying the thrift source code, we do not need to care about these specific data operations.

 

Next, we will perform operations on the client and server, and process specific services on the server.

 

1. Compile an excuse class.

  

Import syssys. path. append (".. /Gen-py ") from CC import hellofrom CC import ttypesclass my_handler (hello. iface): def get_f (self, GG): # Sort Gg objects. A = GG. A + GG. B GG. B = GG. a-GG. B Return gg

The calculatorhandler of the official case does not inherit iface, but here I inherit hello. iface, which has no other meaning. It means that the get_f method of thrift file must be defined. If our logic is more complex, Handler processes database operations, and so on. Inheritance does not inherit iface.

Official handler (Part ):

class CalculatorHandler:    def __init__(self):        self.log = {}    def ping(self):        print 'ping()'    def add(self, n1, n2):        print 'add(%d,%d)' % (n1, n2)        return n1+n2

Next we need to process the handler:

Import syssys. path. append (".. /Gen-py ") from CC import hellofrom CC import ttypesclass my_handler (hello. iface): def get_f (self, GG): # Sort Gg objects. A = GG. A + GG. B GG. B = GG. a-GG. B Return gghandler = my_handler () process = hello. processor (handler) from thrift. transport. tsocket import tserversocketserver = tserversocket (host = "localhost", Port = 9090) from thrift. transport. tTransport import tbufferedtransportfactorytfactory = tbufferedtransportfactory () from thrift. protocol. tbinaryprotocol import tbinaryprotocolfactorybfactory = tbinaryprotocolfactory () from thrift. server. tserver import tsimpleserverservers = tsimpleserver (process, server, tfactory, bfactory) print "starting the server... "servers. serve () print "done..."

Code directly. Note that tserversocket must be specified here, because the host assigns the initial value to write none during the official class initialization, which means no write is performed.

class TServerSocket(TSocketBase, TServerTransportBase):  """Socket implementation of TServerTransport base."""  def __init__(self, host=None, port=9090, unix_socket=None):

What does a service without a host look like? Use netstat-Na to view the Port:

 TCP    [::]:9090              [::]:0                 LISTENING

It is caused by no host.

A host is a service defined as localhost. Use netstat-Na to view the Port:

TCP    127.0.0.1:9090         0.0.0.0:0              LISTENING

 

Next, write the client. The client is mainly used to instantiate the hello. Client object.

_ Author _ = 'cltang '#! -*-Encoding: UTF-8-*-''' client ''' import syssys. path. append (".. /Gen-py ") from CC import hellofrom CC import ttypesfrom thrift. transport Import tsocketfrom thrift. transport Import ttransportfrom thrift. protocol. tbinaryprotocol import tbinaryprotocoltransport = tsocket. tsocket ('localhost', 9090) # buffering is critical. raw sockets are very slowtransport = tTransport. tbufferedtransport (Transport) # wrap in a protocolprotocol = tbinaryprotocol (Transport) Client = hello. client (Protocol) transport. open () FF = Ttypes. f (a = 1, B = 2) Results = client. get_f (FF) print resultstransport. close ()

Execute the client program and output the following:

f(a=3, c='helloworld', b=1, e={'cc': 'dd', 'ee': 'ff'}, d=['hello', 'world'])

It reaches the content of the service we first defined in test. Thrift, that is, an F-Type instantiated object is passed in, the get_f method is called, And a processed F-Type instantiated object is returned.

 

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.