Enterprise Integration Zone is brought to you in partnership with:

A computer science undergraduate at University of Colombo. Pavithra is a DZone MVB and is not an employee of DZone and has posted 16 posts at DZone. You can read more from them at their website. View Full User Profile

Apache Thrift with Java Quickstart

07.15.2012
| 14513 views |
  • submit to reddit
Apache Thrift is a RPC framework founded by facebook and now it is an Apache project. Thrift lets you define data types and service interfaces in a language neutral definition file. That definition file is used as the input for the compiler to generate code for building RPC clients and servers that communicate over different programming languages. You can refer Thrift white paper also.

According to the official web site Apache Thrift is a,
software framework, for scalable cross-language services development, combines a software stack with a code generation engine to build services that work efficiently and seamlessly between C++, Java, Python, PHP, Ruby, Erlang, Perl, Haskell, C#, Cocoa, JavaScript, Node.js, Smalltalk, OCaml and Delphi and other languages.
Image courtesy wikipedia


Installing Apache Thrift in Windows

Installation Thrift can be a tiresome process. But for windows the compiler is available as a prebuilt exe. Download thrift.exe and add it into your environment variables.

Writing Thrift definition file (.thrift file)

Writing the Thrift definition file becomes really easy once you get used to it. I found this tutorial quite useful to begin with.

Example definition file (add.thrift)

namespace java com.eviac.blog.samples.thrift.server  // defines the namespace   
      
    typedef i32 int  //typedefs to get convenient names for your types  
      
    service AdditionService {  // defines the service to add two numbers  
            int add(1:int n1, 2:int n2), //defines a method  
    }  

Compiling Thrift definition file

To compile the .thrift file use the following command. 

thrift --gen <language> <Thrift filename>  

For my example the command is, 

thrift --gen java add.thrift  

After performing the command, inside gen-java directory you'll find the source codes which is useful for building RPC clients and server. In my example it will create a java code called AdditionService.java

Writing a service handler

Service handler class is required to implement the AdditionService.Iface interface.

Example service handler (AdditionServiceHandler.java)

 
package com.eviac.blog.samples.thrift.server;

import org.apache.thrift.TException;

public class AdditionServiceHandler implements AdditionService.Iface {

 @Override
 public int add(int n1, int n2) throws TException {
  return n1 + n2;
 }

}

Writing a simple server

Following is an example code to initiate a simple thrift server. To enable the multithreaded server uncomment the commented parts of the example code.

Example server (MyServer.java)

package com.eviac.blog.samples.thrift.server;

import org.apache.thrift.transport.TServerSocket;
import org.apache.thrift.transport.TServerTransport;
import org.apache.thrift.server.TServer;
import org.apache.thrift.server.TServer.Args;
import org.apache.thrift.server.TSimpleServer;

public class MyServer {

 public static void StartsimpleServer(AdditionService.Processor<AdditionServiceHandler> processor) {
  try {
   TServerTransport serverTransport = new TServerSocket(9090);
   TServer server = new TSimpleServer(
     new Args(serverTransport).processor(processor));

   // Use this for a multithreaded server
   // TServer server = new TThreadPoolServer(new
   // TThreadPoolServer.Args(serverTransport).processor(processor));

   System.out.println("Starting the simple server...");
   server.serve();
  } catch (Exception e) {
   e.printStackTrace();
  }
 }
 
 public static void main(String[] args) {
  StartsimpleServer(new AdditionService.Processor<AdditionServiceHandler>(new AdditionServiceHandler()));
 }

}

Writing the client

Following is an example java client code which consumes the service provided by AdditionService.

Example client code (AdditionClient.java)

package com.eviac.blog.samples.thrift.client;

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;

public class AdditionClient {

 public static void main(String[] args) {

  try {
   TTransport transport;

   transport = new TSocket("localhost", 9090);
   transport.open();

   TProtocol protocol = new TBinaryProtocol(transport);
   AdditionService.Client client = new AdditionService.Client(protocol);

   System.out.println(client.add(100, 200));

   transport.close();
  } catch (TTransportException e) {
   e.printStackTrace();
  } catch (TException x) {
   x.printStackTrace();
  }
 }

}

Run the server code(MyServer.java). It should output following and will listen to the requests.

Starting the simple server...  

Then run the client code(AdditionClient.java). It should output following. 

300  

 

Published at DZone with permission of Pavithra Gunasekara, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Comments

Viraf Karai replied on Mon, 2014/02/10 - 6:11pm

Well written article. It helped me to set up a a Thrift project quickly on my Linux workstation. Unfortunately, the Thrift compiler for Java (on Linux) results in code that doesn't compile (nothing to do with the article at all). The syntax errrors are easy to fix and mainly deal with implementation methods that should be public but are set to protected by the Thrift compiler for Java on Linux.

I enjoyed the article. Thank you for sharing your wisdom. Thrift is quite easy and enjoyable to use.

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.