Thrift Java and PHP data interaction

Source: Internet
Author: User

Thrift is a software framework (Remote Procedure Call framework) for the development of extensible and cross-language services, encapsulating the service framework for data transfer formats (binary, JSON) and network communication, available in multiple languages (c + +, Java, Python, PHP, Ruby, Erlang, Network server side and client program components for Perl, Haskell, C #, Cocoa, JavaScript, node. js, Smalltalk, and OCaml)

For large-scale data exchange and storage of common tools, for large systems in the internal data transmission in relation to JSON and XML in terms of performance, transmission size has obvious advantages.

This article takes the registration service interface and the login server interface as a tutorial,

Several concepts developed by thrift:

Server Service Model

Handler Data Processing interface

Processor Data Processing objects

Protocol Data Transfer Protocol

Transport Data transfer method


(1) Supported transfer formats

tbinaryprotocol– in binary format.

tcompactprotocol– compression format

Tjsonprotocol–json format

tsimplejsonprotocol– provides JSON-only write-only protocols, and the resulting files are easily parsed by scripting languages.

tdebugprotocol– use easy-to-read, readable text format for debug

(2) Supported communication mode (data transmission mode) (Transport)

Tfiletransport: File (log) transport class, which allows the client to pass files to the server, allowing the server to write the received data to a file.

Thttptransport: Using HTTP Transport protocol for data transfer

Tsocket: Using a TCP socket for data transfer

Tzlibtransport: Transfers data after compression, or extracts received data

The following classes are mainly decorated with the above categories (using decorative mode) to improve transmission efficiency.

Tbufferedtransport: Buffer of data that is manipulated by a transport object, which reads data from buffer, or writes data directly to buffer

Tframedtransport: Used in a non-blocking service with frame as the transmission unit. Similar to Tbufferedtransport, buffer is also available for the relevant data, and it supports fixed-length data sending and receiving.

Tmemorybuffer: Reading and writing data from a buffer


(3) Supported service models

tsimpleserver– Simple single-threaded service model, often used for testing

Tthreadedserver-Multithreaded service model that uses blocking IO to create one thread per request.

The tthreadpoolserver– thread pool service model uses standard blocking IO to pre-create a set of thread processing requests.

tnonblockingserver– multithreaded service model with non-blocking IO (using Tframedtransport data transfer method)

To deal with a lot of updates, the main thing is to choose between Tthreadedserver and Tnonblockingserver. Tnonblockingserver can handle a large number of concurrent connections with a small number of threads, but with a high latency and low tthreadedserver latency. In practice, tthreadedserver throughput may be higher than tnonblockingserver, but tthreadedserver CPU consumption is much higher than tnonblockingserver.


General steps written by the server:

1. Create Handler

2. Create processor based on handler

3. Create transport (communication mode)

4. Create protocol mode (set transfer format)

5. Create a server based on processor, transport, and protocol

6. Run the server

General steps written by the client:

1. Create Transport

2. Create Protocol Mode

3. Create a client based on transport and Protocol

4. How to run the client

Above overview content reference from: http://elf8848.iteye.com/blog/1960131

Start the official code tutorial below

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<t1,t2>  map  from one&nbsP;type to another *  list<t1>    ordered list of  one type *  set<t1>     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&NBSP;PSW);}  service registerservice{    user createuser (1:string name, 2: STRING&NBSP;PSW);}

Using thrift to generate the corresponding platform language code

Thrift-gen Java Test.thrift

Thrift-gen PHP Test.thrift

If PHP needs to build the server side, the requirement changes to Thrift-gen php:server Test.thrift

Java

Implement Loginserviceimpl.java Login Interface Service

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.seti D (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);//  User Login Loginservice.processor loginprocessor = new loginservice.processor (new  Loginserviceimpl ());//  User Registration 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 ();p rocessor.registerprocessor ( "Loginservice",  loginprocessor);p rocessor.registerprocessor ("Registerservice",  registerprocessor); Tserver server = new tthreadpoolserver (New tthreadpoolserver.args (ServerTransport). Processor (processor)); System.out.println ("STARTING&NBSP;SERVER&NBSP;ON&NBSP;PORT&NBSP;7911&NBSP; ..."); 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); Tmultiplexedprotocol mp1 = new tmultiplexedprotocol (Protocol, "Loginservice");//  Tprotocol protocol = 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); Transport.open (); User user = loginclient.login ("Penngo",  "123");if  (user != null)  { SYSTEM.OUT.PRINTLN ("Login succeeded:"  + user.getid ()  +  " " + user.getname ());} &NBSP;ELSE&NBSP;{SYSTEM.OUT.PRINTLN ("Login Failed");} User user2 = registerclient.createuser ("Test",  "123");if  (User2 != null) &NBSP;{SYSTEM.OUT.PRINTLN ("Create User success:"  + user2.getid ()  +  " " + user2.getname ());} &NBSP;ELSE&NBSP;{SYSTEM.OUT.PRINTLN ("Create user Failed");} Transport.close ();}  catch  (texception x)  {x.printstacktrace ();}}

Client PHP

<?phpnamespace com\penngo;require_once __dir__. ' /.. /.. /lib/thrift/classloader/thriftclassloader.php ';//echo __dir__. ' /.. /.. /lib/thrift/classloader/thriftclassloader.php ';use thrift\classloader\thriftclassloader; $GEN _dir =  realpath (DirName (__file__)). ' /.. /.. /gen-php '; $loader  = new thriftclassloader (); $loader->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 ";}?" >


Thrift Java and PHP data interaction

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.