[Zz] Use thrift for c ++, java and python call each other [zz] Use thrift for c ++, java and python call each other

Source: Internet
Author: User

[Zz] Using thrift for c ++, mutual calls between java and python-zareilynn-blog Park

[Zz] Using thrift for c ++, java and python calls each other

To install thrift on linux, see
Http://jinghong.iteye.com/blog/1102535
Thrift, as a cross-language calling solution, has the advantages of high efficiency, many languages, and maturity. Strong code intrusion is its weakness.
The following is an example of using C ++ as the server, C ++, java, and python as the client. This is consistent with my current working environment, A multi-threaded persistent connection socket is used to establish a cross-language calling platform for an efficient distributed system.
Unfortunately, the c language of the current version (0.7.0) does not support the Compact Protocol. As a result, the nginx c module uses the binary protocol to call thrift in the current environment. The thrift development team seems not familiar with C language.
1. Define the idl file acsuser. thrift
Idl code collection code

Struct User {
1: string uid,
2: string uname,
3: bool usex,
4: i16 uage,
}
Service UserService {
Void add (1: User u ),
User get (1: string uid ),
}

2. Generate a c ++, java, and python code framework
Shell code favorites code

Thrift-r -- gen cpp acsuser. thrift
Thrift-r -- gen java acsuser. thrift
Thrift-r -- gen py acsuser. thrift

In this case, the subdirectories gen-cpp, gen-java, and gen-py are generated.

3. generate C ++ server code
Shell code favorites code

Cp gen-cpp/UserService_server.skeleton.cpp UserServer. cpp

Modify UserServer. cpp
C ++ code

# Include "UserService. h"
# Include <config. h>
// # Include <protocol/TBinaryProtocol. h>
# Include <protocol/TCompactProtocol. h>
# Include <server/TSimpleServer. h>
# Include <transport/TServerSocket. h>
# Include <transport/TBufferTransports. h>
# Include <concurrency/ThreadManager. h>
# Include <concurrency/PosixThreadFactory. h>
# Include <server/TThreadPoolServer. h>
# Include <server/TThreadedServer. h>

Using namespace: apache: thrift;
Using namespace: apache: thrift: protocol;
Using namespace: apache: thrift: transport;
Using namespace: apache: thrift: server;
Using namespace: apache: thrift: concurrency;

Using boost: shared_ptr;

Class UserServiceHandler: virtual public UserServiceIf {
Public:
UserServiceHandler (){
// Your initialization goes here
}

Void add (const User & u ){
// Your implementation goes here
Printf ("uid = % s uname = % s usex = % d uage = % d \ n", u. uid. c_str (), u. uname. c_str (), u. usex, u. uage );
}

Void get (User & _ return, const std: string & uid ){
// Your implementation goes here
_ Return. uid = "leo1 ";
_ Return. uname = "yueyue ";
_ Return. usex = 1;
_ Return. uage = 3;
Printf ("uid = % s uname = % s usex = % d uage = % d \ n", _ return. uid. c_str (), _ return. uname. c_str (), _ return. usex, _ return. uage );
}

};

Int main (int argc, char ** argv ){
Shared_ptr <UserServiceHandler> handler (new UserServiceHandler ());
Shared_ptr <TProcessor> processor (new UserServiceProcessor (handler ));
Shared_ptr <TProtocolFactory> protocolFactory (new TCompactProtocolFactory ());
Shared_ptr <TTransportFactory> transportFactory (new TBufferedTransportFactory ());
Shared_ptr <TServerTransport> serverTransport (new TServerSocket (9090 ));

Shared_ptr <ThreadManager> threadManager = ThreadManager: newSimpleThreadManager (10 );
Shared_ptr <PosixThreadFactory> threadFactory = shared_ptr <PosixThreadFactory> (new PosixThreadFactory ());
ThreadManager-> threadFactory (threadFactory );
ThreadManager-> start ();
Printf ("start user server... \ n ");

TThreadPoolServer server (processor, serverTransport, transportFactory, protocolFactory, threadManager );
Server. serve ();
Return 0;
}

Note that this Code uses TCompactProtocol and # include <config. h> is required.
In addition, this is a Blocking multi-thread server.

4. Generate the client file UserClient. cpp of C ++
C ++ code

# Include "UserService. h"
# Include <config. h>
# Include <transport/TSocket. h>
# Include <transport/TBufferTransports. h>
# Include <protocol/TCompactProtocol. h>

Using namespace apache: thrift;
Using namespace apache: thrift: protocol;
Using namespace apache: thrift: transport;

Using boost: shared_ptr;

Int main (int argc, char ** argv ){
Boost: shared_ptr <TSocket> socket (new TSocket ("localhost", 9090 ));
Boost: shared_ptr <TTransport> transport (new TBufferedTransport (socket ));
Boost: shared_ptr <TProtocol> protocol (new TCompactProtocol (transport ));

Transport-> open ();

User u;
U. uid = "leo ";
U. uname = "yueyue ";
U. usex = 1;
U. uage = 3;

UserServiceClient client (protocol );
Client. add (u );

User u1;
Client. get (u1, "lll ");

Transport-> close ();
Printf ("uid = % s uname = % s usex = % d uage = % d \ n", u1.uid. c_str (), u1.uname. c_str (), u1.usex, u1.uage );
Return 0;
}

5. Generate Makefile
Makefile code favorites code

BOOST_DIR =/usr/local/include/boost/
THRIFT_DIR =/usr/local/include/thrift
LIB_DIR =/usr/local/lib
GEN_SRC =./gen-cpp/acsuser_types.cpp./gen-cpp/acsuser_constants.cpp./gen-cpp/UserService. cpp
Default: server client
Server: UserServer. cpp
G ++-g-o UserServer-I $ {THRIFT_DIR}-I $ {BOOST_DIR}-I. /gen-cpp-L $ {LIB_DIR}-lthrift UserServer. cpp $ {GEN_SRC}
Client: UserClient. cpp
G ++-g-o UserClient-lm-pthread-lz-lrt-lssl-I $ {THRIFT_DIR}-I $ {BOOST_DIR}-I. /gen-cpp-L $ {LIB_DIR}-lthrift UserClient. cpp $ {GEN_SRC}
Clean:
$ (RM)-r UserServer UserClient

6. Start c ++ server
Shell code favorites code

./UserServer

7. Test c ++ client
Shell code favorites code

./UserClient

8. Write the java client file UserClient. java
Java code collection code

Import org. apache. thrift. TException;
Import org. apache. thrift. protocol. TCompactProtocol;
Import org. apache. thrift. protocol. TProtocol;
Import org. apache. thrift. transport. TFramedTransport;
Import org. apache. thrift. transport. TNonblockingSocket;
Import org. apache. thrift. transport. TSocket;
Import org. apache. thrift. transport. TTransport;
Import org. apache. thrift. transport. TTransportException;

// Import UserService. Client;

Public class UserClient {
Private void start (){
Try {
TTransport socket = new TSocket ("localhost", 9090 );
// TTransport transport = new TFramedTransport (socket );
TProtocol protocol = new TCompactProtocol (socket );

UserService. Client client = new UserService. Client (protocol );
Socket. open ();
System. out. println (client. get ("lll "));

User u = new User ();
U. uid = "leojava ";
U. uname = "yueyue ";
U. usex = true;
U. uage = 3;
Client. add (u );
Socket. close ();

} Catch (TTransportException e ){
E. printStackTrace ();
} Catch (TException e ){
E. printStackTrace ();
}
}

Public static void main (String [] args ){
UserClient c = new UserClient ();
C. start ();

}
}

Compile and run java client
Shell code favorites code

Javac-classpath/usr/local/lib/libthrift-0.7.0.jar:/usr/local/lib/log4j-1.2.14.jar:/usr/local/lib/commons-logging-1.1.1.jar:/usr/local/lib/slf4j-api-1.5.8.jar UserClient. java. /gen-java /*. java
Java-classpath. :. /gen-java:/usr/local/lib/libthrift-0.7.0.jar:/usr/local/lib/log4j-1.2.14.jar:/usr/local/lib/commons-logging-1.1.1.jar: /usr/local/lib/slf4j-api-1.5.8.jar:/usr/local/lib/slf4j-log4j12-1.5.8.jar UserClient

9. Write Python client file PythonClient. py
Add Python code to favorites

#! /Usr/bin/env python
Import sys
Sys. path. append ('./gen-py ')
From acsuser import UserService
From acsuser. ttypes import *
From thrift import Thrift
From thrift. transport import TSocket
From thrift. transport import TTransport
From thrift. protocol import TCompactProtocol

# Make socket
Transport = TSocket. TSocket ('localhost', 9090)
# Buffering is critical. Raw sockets are very slow
Transport = TTransport. TBufferedTransport (transport)
# Wrap in a protocol
Protocol = TCompactProtocol. TCompactProtocol (transport)
# Create a client to use the protocol encoder
Client = UserService. Client (protocol)
# Connect!
Transport. open ()
# Call Server services
U = client. get ('lll ')
Print 'uid = % s uname = % s usex = % d u. uage = % d' % (u. uid, u. uname, u. usex, u. uage)

U1 = User ()
U1.uid = 'Leo'
U1.uname = 'yueyue'
U1.usex = 1
U1.uage = 3
Client. add (u1)

Execute python client code
Shell code favorites code

Chmod 777 PythonClient. py
./PythonClient. py

Sample.tar.gz (2.1 KB)
Description: source file.
Downloads: 22

Category: thrift

Related Article

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.