Thursday, September 22, 2011

Writing Your First Thrift Service

Thrift provides a Binary RPC protocol for supporting service invocations, and it provides toolkits to generate thrift binding for several languages, including Java, C, C++ etc. Then just like with Web Services, the thrift service invocations will agree on the wire and enable multiple programming language implementations to talk to each other.

If you remember  CORBA, it was the same thing. Well except for the fact that it was nightmare to write a service using CORBA tools.

Well why am I interested with Thrift? Well simple answer is it is fast, and has lot of traction.

Luckily writing a thrift service is pretty easy. Following is how I did it.

  1. Download and build thrift from Look at README for instructions. However, I had to disable Erlang binding while running ./configure ( --without-erlang). 
  2. Then first step is to write the thrift IDL. Mine did looked like following. is the best source to learn how to write a Thrift IDL.
    namespace java Test
    struct Tuple {
      1: list tuples,
    service Bissa {
    void put(1:Tuple tuple),
    list read(1:string pattern),
    list take(1:string pattern)
  3. The I ran thrift to generate code. Command looked like thrift --gen java bissa.thrift. 
  4. Above created a service class and types define in the IDL. Then I wrote a server that uses the generated code and it looked like following. Sample class can be found from
    //This is a class that implement Bissa.Iface interface (class generated by thrift to represent the service. )
    BissaThriftServer handler = new BissaThriftServer(bissa);
    //then we initialize a processor passing that handler (implementation)
    Bissa.Processor processor = new Bissa.Processor(handler);
    TServerTransport serverTransport = new TServerSocket(thriftPort);
    // Use this for a multithreaded server
    TServer server = new TThreadPoolServer(new TThreadPoolServer.Args(serverTransport).processor(processor));
    System.out.println("Starting the simple server... on port "+ thriftPort);
  5. Client looked like following. 
     TTransport transport;
    transport = new TSocket("localhost", 9092);;
    TProtocol protocol = new TBinaryProtocol(transport);
    //following is generated code
    Bissa.Client client = new Bissa.Client(protocol);
    //now u have a stub, use it
    client.put(BissaThriftServer.createTuple("A", "B"));
  6. You might also find this blog useful. 


Robert Clove said...

Sir can the Thrift Service be written in dot net?

Srinath Perera said...