Thrift-java instances

Source: Internet
Author: User

? more technical dry please poke: Listen to the Cloud blog

Thrift Example 1

Function Description: The client and server side is two applications, first start the server side, and then start the client, implementation of the client running the server side of the addition method.

Source code (source in the annex):

Client:

Testthriftclientservlet:

Sendrequestcontroller:

Pom.xml:

Service side:

Testthriftservlet:

Thriftservercontroller:

Ithriftserver: Generated by Thrift tool compilation

Thriftserverserviceimpl:

Operating instructions: First run the server Testthriftservlet, then run the client Testthriftclientservlet, watch the console print 81, namely: 77+5=81

Thrift Example 2

1, Business logic Description: A system through the user ID number of the other system for the user's points.

2, first write script file Test.thrift:

Namespaces:

namespace Java com.test

namespace is a keyword that represents a namespace, that is, a Java package, and Java means that the script is converted to a Java class

Request: Identitycard is a social security number

struct Userrequest{1:string Identitycard}

Return: Code is a successful identity 0 means success; Integral is a user-owned integral

The params is a collection of parameters that are returned here using only one field integral (integral) as an example;

struct userresponse{1:string code2:map<string,string> Params}

Service:

Service Thriftcase{userresponse Integralservice (1:userrequest request)}

3, to thrift official website download

http://thrift.apache.org/

Download: thrift-0.6.1.tar.gz and thrift Compiler for Windows (Thrift-0.6.1.exe)

4, use the Ant tool inside the eclips to compile the thrift-0.6.1 jar package

Decompression: thrift-0.6.1.tar.gz

Put the unpacked folder under one of Eclipse's projects

If the thrift-0.6.1 folder is placed under the name of the Thrift Java Project SRC, there is a red fork do not have to control him, and then into the Thrift-0.6.1/lib/java, right click on the Build.xml

Click Ant Build. A build folder with the generated Thrift-0.6.1.jar package will be generated under the Build.xml same path. Put this bag in the Lib of the project you are doing.

5. Compile the thrift script into Java class

Put the Thrift-0.6.1.exe and Test.thrift files in the same directory and write the path into the environment variable path, such as: e:/soft/ccc/path into the above two files and write the path into the environment variable path.

In the run, type cmd to open the DOS interface, go to the e:/soft/ccc/path, execute the thrift-0.6.1.exe file, and command the following:

E:\soft\ccc\>thrift-0.6.1–gen Java Text.thrift

In this directory will produce a Gen-java folder, the folder will produce the corresponding Java class,

Thriftcase.java

Userrequest.java

Userresponse.java

Copy the three files to the src/com/test/path of the thrift project.

6. Write service-side code

The server-side code contains two classes: one is the business logic class and one is the socket service class.

Business logic class to implement Thriftcase.iface service interface

Package Com.test;import Java.util.hashmap;import Java.util.map;public class Thriftcaseimpl implements Thriftcase.iface{public userresponse Integralservice (userrequest request) {Try{userresponse urp=new UserResponse (); if (Request.identitycard.equals ("32010619881231103X")) {Urp.setcode ("0"); Map params=new HashMap ();p arams.put ("Integral", "ten"); Urp.setparams (params);} System.out.print ("Receive parameter is: identitycard=" +request.identitycard); return urp;} catch (Exception e) {e.printstacktrace ();} return null;}}

Socket service Class

package com.test;import org.apache.thrift.protocol.tbinaryprotocol;import  org.apache.thrift.protocol.tbinaryprotocol.factory;import org.apache.thrift.server.tserver;import  Org.apache.thrift.server.tthreadpoolserver;import org.apache.thrift.server.tthreadpoolserver.args;import  org.apache.thrift.transport.TServerSocket;import org.apache.thrift.transport.TTransportException; Public class testservice {private void start () {try {tserversocket  Servertransport = new tserversocket (8899); Thriftcase.processor processor = new thriftcase.processor (New ThriftCaseImpl ());// tbinaryprotocol –  binary encoded format for data transfer. Factory protfactory = new tbinaryprotocol.factory (true,true);//TCompactProtocol  This protocol is very effective, using variable-length quantity  (VLQ)   encoding to compress the data//factory protfactory = new  tcompactprotocol.factory (); Args args = new&nBsp Args (Servertransport); Args.processor (processor); Args.protocolfactory (protfactory); Tserver server = new tthreadpoolserver (args); System.out.println ("STARTING&NBSP;SERVER&NBSP;ON&NBSP;PORT&NBSP;8899&NBSP; ..."); Server.serve ();}  catch  (ttransportexception e)  {e.printstacktrace ();}  catch  (exception e)  {e.printstacktrace ();}} Public static void main (String[] args)  {// todo auto-generated method  stubtestservice srv = new testservice (); Srv.start ();}}

package com.test;import org.apache.thrift.texception;import  org.apache.thrift.protocol.tbinaryprotocol;import org.apache.thrift.protocol.tprotocol;import  org.apache.thrift.transport.tsocket;import org.apache.thrift.transport.ttransport;import  org.apache.thrift.transport.ttransportexception;import com.test.thriftcase.client;public class  Testclient {private void start ()  {         ttransport transport;        try {             transport = new tsocket ("localhost",  8899) ;            tprotocol protocol =  New tbinaryprotocol (transport);             Client client = new client (protocol);                                     UserRequest  Request=new userrequest ();             Request.setidentitycard ("32010619881231103X");                         transport.open ();             com.test.userresponse urp= Client.integralservice (request);             if ( Urp.code!=null&&!urp.code.equals ("")) {             system.out.println ("Return code:" +urp.code+ ";  parameter is:" +urp.params.get ("Integral"));            &nbSP;}             transport.close ();         } catch  (ttransportexception e)  {             e.printstacktrace ();         } catch  (texception e)  {             e.printstacktrace ();         }    }     public static void main (String[] args)  {         testclient c = new testclient ();             c.start ();     }}

8. Open the service first

public static void Main (string[] args) {//TODO auto-generated method Stubtestservice srv = new Testservice (); Srv.start (); The console displays: Starting server on port 8899 ...

9. Run the client again

public static void Main (string[] args) {testclient c = new TestClient ();    C.start (); }

Console display:

Return code: 0; Parameters are: 10

10, the required third-party package

log4j-1.2.15,

Slf4j-api-1.6.1.jar

Slf4j-log4j12-1.5.8.jar

Original link: http://blog.tingyun.com/web/article/detail/1082

Thrift-java instances

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.