Thrift's java and php Data interaction

Source: Internet
Author: User
Thrift's java and php Data interaction Thrift is a software framework (remote process call Framework) used to develop scalable and cross-language services, it encapsulates the data transmission format (binary, json) and network communication service framework, and provides multilingual (C ++, Java, Python, PHP, Ruby, Erlang, Perl, Haskell, C #, Cocoa, JavaScript, Node. js, Smalltalk, and OCaml) network server and client program components

This tool is suitable for building large-scale data exchange and storage tools. for large systems, internal data transmission has obvious advantages over JSON and xml in terms of performance and transmission size.

This document describes how to register a service interface and a logon server interface,

Several Thrift development concepts:

Server Service model

Handler data processing interface

Processor Data processing object

Protocol data transmission Protocol

Transport data transmission mode


(1) supported transmission formats

TBinaryProtocol? Binary format.

TCompactProtocol? Compression Format

TJSONProtocol? JSON format

TSimpleJSONProtocol? JSON write-only protocol is provided, and the generated files are easily parsed using the script language.

TDebugProtocol? Easy-to-understand and readable text format for debugging

(2) supported Communication (data transmission) (Transport)

TFileTransport: a file (log) transmission class that allows the client to send files to the server and allow the server to write received data to the file.

THttpTransport: data transmission over Http

TSocket: uses TCP Socket for data transmission

TZlibTransport: transfers data after compression, or decompress the received data.

The following categories are mainly used to decorate the above categories (using the decorative mode) to improve transmission efficiency.

TBufferedTransport: buffer the data operated by a Transport object, that is, the data is read from the buffer for transmission, or the data is directly written to the buffer.

TFramedTransport: frame-based transmission, which is used in non-blocking services. Similar to TBufferedTransport, it also performs buffer on the relevant data and supports sending and receiving of fixed-length data.

TMemoryBuffer: reads and writes data from a buffer.


(3) supported service models

TSimpleServer? Simple single-threaded service model, often used for testing

TThreadedServer-multi-threaded service model, using blocking IO, each request creates a thread.

TThreadPoolServer? The thread pool service model uses standard blocking IO to pre-create a set of threads to process requests.

TNonblockingServer? Multi-threaded service model with non-blocking I/O (TFramedTransport data transmission is required)

When processing a large number of updates, you can select TThreadedServer and TNonblockingServer. TNonblockingServer can use a small number of threads to process a large number of concurrent connections, but the latency is high. TThreadedServer has a low latency. In practice, the TThreadedServer throughput may be higher than that of TNonblockingServer, but the CPU usage of TThreadedServer is much higher than that of TNonblockingServer.


General steps for writing on the server:

1. create Handler

2. create Processor based on Handler

3. create a Transport (communication mode)

4. create a Protocol (set the transmission format)

5. create a Server based on Processor, Transport, and Protocol

6. run Server

General steps for writing a client:

1. create a Transport

2. create Protocol

3. create a Client based on Transport and Protocol

4. how to run the Client

Refer to the following content for the above overview:

The following is a formal code tutorial.

Service description file test. thrift, which defines the login service and register

/** * The first thing to know about are types. The available types in Thrift are: * *  bool        Boolean, one byte *  byte        Signed byte *  i16         Signed 16-bit integer *  i32         Signed 32-bit integer *  i64         Signed 64-bit integer *  double      64-bit floating point value *  string      String *  binary      Blob (byte array) *  map
 
    Map from one type to another *  list
  
       Ordered list of one type *  set
   
         Set of unique elements of one type * * Did you also notice that Thrift supports C style comments? */namespace java com.penngonamespace php com.penngostruct User {1: i64 id,2: string name,3: string password}service LoginService{    User login(1:string name, 2:string psw);} service RegisterService{    User createUser(1:string name, 2:string psw);}
   
  
 

Use thrift to generate the corresponding platform language code

Thrift-gen java test. thrift

Thrift-gen php test. thrift

If php needs to generate a server, change it to thrift-gen php: server test. thrift.

Java

Implement LoginServiceImpl. java login interface business

import org.apache.thrift.TException;public class LoginServiceImpl implements LoginService.Iface{public LoginServiceImpl(){}public User login(String name, String psw) throws TException{User user = null;if(name.equals("penngo") && psw.equals("123")){user = new User();user.setId(1);user.setName("penngo");}return user;}}

Implement RegisterServiceImpl. java registration interface business

import org.apache.thrift.TException;public class RegisterServiceImpl implements RegisterService.Iface{public RegisterServiceImpl(){}public User createUser(String name, String psw) throws TException{User user = new User();user.setId(2);user.setName(name);user.setPassword(psw);return user;}}

Server-side java code

Package com. penngo. main; import org. apache. thrift. TMultiplexedProcessor; 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 com. penngo. loginService; import com. penngo. loginServiceImpl; import com. penngo. registerService; import com. penngo. registerServiceImpl; public class Server {private void start () {try {TServerSocket serverTransport = new TServerSocket (7911); // log on to LoginService. processor loginProcessor = new LoginService. processor (new LoginServiceImpl (); // You can register RegisterService. processor registerProcessor = new RegisterService. processor (new RegisterServiceImpl (); // Factory protFactory = new TBinaryProtocol. factory (true, true); // TServer server = new TThreadPoolServer (new // TThreadPoolServer. args (serverTransport )//. processor (loginProcessor); TMultiplexedProcessor processor = new TMultiplexedProcessor (); processor. registerProcessor ("LoginService", loginProcessor); processor. registerProcessor ("RegisterService", registerProcessor); TServer server = new TThreadPoolServer (new TThreadPoolServer. args (serverTransport ). processor (processor); System. out. println ("Starting server on port 7911... "); server. serve ();} catch (TTransportException e) {e. printStackTrace ();} catch (Exception e) {e. printStackTrace () ;}} public static void main (String args []) {Server srv = new Server (); srv. start ();}}

Client java

Package com. penngo. main; import org. apache. thrift. *; import org. apache. thrift. protocol. *; import org. apache. thrift. transport. *; import com. penngo. loginService; import com. penngo. registerService; import com. penngo. user; public class Client {public static void main (String [] args) {try {TTransport transport = new TSocket ("localhost", 7911 ); TProtocol protocol = new TBinaryProtocol (transport); TMultiplexedProto Col mp1 = new TMultiplexedProtocol (protocol, "LoginService"); // TProtocol = new TBinaryProtocol (transport); // LoginService. client client = new LoginService. client (protocol); LoginService. client loginClient = new LoginService. client (mp1); TMultiplexedProtocol mp2 = new TMultiplexedProtocol (protocol, "RegisterService"); RegisterService. client registerClient = new RegisterService. client (mp2); tran Sport. open (); User user = loginClient. login ("penngo", "123"); if (user! = Null) {System. out. println ("logon successful:" + user. getId () + "" + user. getName ();} else {System. out. println ("logon failed");} User user2 = registerClient. createUser ("test", "123"); if (user2! = Null) {System. out. println ("User created successfully:" + user2.getId () + "" + user2.getName ();} else {System. out. println ("failed to create user");} transport. close ();} catch (TException x) {x. printStackTrace ();}}}

Client php

 registerNamespace('Thrift', __DIR__ . '/../../lib');//$loader->registerDefinition('shared', $GEN_DIR);$loader->registerDefinition('com', $GEN_DIR);$loader->register();if (php_sapi_name() == 'cli') {    ini_set("display_errors", "stderr");}use Thrift\Protocol\TBinaryProtocol;use Thrift\Protocol\TMultiplexedProtocol;use Thrift\Transport\TSocket;use Thrift\Transport\THttpClient;use Thrift\Transport\TBufferedTransport;use Thrift\Exception\TException;use com\penngo\RegisterServiceClient;use com\penngo\LoginServiceClient;try {    if (array_search('--http', $argv)) {        //$socket = new THttpClient('localhost', 8080, '/php/PhpServer.php');    } else {        $socket = new TSocket('localhost', 7911);    }    $transport = new TBufferedTransport($socket, 1024, 1024);    $protocol = new TBinaryProtocol($transport);    $loginProtocol = new TMultiplexedProtocol($protocol, "LoginService");    $registerProtocol = new TMultiplexedProtocol($protocol, "RegisterService");    $loginClient = new LoginServiceClient($loginProtocol);    $registerClient = new RegisterServiceClient($registerProtocol);    $transport->open();    $user = $loginClient->login('penngo', '123');    print "user===={$user->id} {$user->name} \n";        $user = $registerClient->createUser('test', '123456');    print "user===={$user->id} {$user->name} \n";    $transport->close();} catch (TException $tx) {    print 'TException: '.$tx->getMessage()."\n";    print 'TException: '.$tx->getTraceAsString()."\n";}?>

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.