/thrift-example

an example for nodejs talking to java via thrift

Primary LanguageJava

Thrift is the Apache Thrift 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.

For more infomations, see http://thrift.apache.org/.

Here is an example for nodejs client communicating with java server.

Thrift needs a .thrift file written in IDL, then a thrift compiler will compile this .thrift file to the language local code,and witch language it compiles to depends on the arguments you passed in. Then we will use the local code to communicate with each other.

1.So, first we need the .thrift compiler. In the thrift folder,there is an already built compiler thrift-0.9.3.exe. If you are trying to build yourself, you can unzip the thrift-0.9.3.tar.gz in the thrift folder, then open the compiler folder in the unzipped files, then you can build it.

2.When the compiler is ready, we can write a Calc.thrift file. You can find it in the root folder.

Calc.thrift


	struct Message {
	  1: string mes
	}
	
	service Calc {
		i32 add(1:i32 num1, 2:i32 num2),
		Message hello(1:Message name)
	}

3.Now we need to compile this Calc.thrift file into java and nodejs code. If you rename thrift-0.9.3.exe to thrift.exe and added it to PATH, you can do this as gen.bat does:

	thrift -r --gen java Calc.thrift
	thrift -r --gen js:node Calc.thrift

4.Then you will find there are two new folders called gen-java and gen-nodejs.

5.Now we will build a java server. First we import those two files in gen-java into a Eclipse java project, then we need to add some dependencies to the project. What we need can all be found in that unzipped thrift-0.9.3.tar.gz. But we have to run an ant task to get what we need. cd to the folder thrift-0.9.3/lib/java, then run ant , when the task is finished, we can find a build folder, get into it, we can find libthrift-0.9.3.jar in there, this is the most important jar we depends on. Also, those java in the build/lib folder are almost needed.

6.Now we need to code something to build the server. We will create two java classes: CalcHandler which implements the interface we defined in our Calc.thrift, and JavaServer which is the server for handling the requests from any client. I put these two files in the folder gen-java with the generated code.

CalcHandler.java


	import org.apache.thrift.TException;
	
	public class CalcHandler implements Calc.Iface {
	
		@Override
		public int add(int num1, int num2) throws TException {
			return num1 + num2;
		}
	
		@Override
		public Message hello(Message name) throws TException {
			return new Message("hello " + name.mes);
		}
	}

JavaServer.java

	
	import org.apache.thrift.server.TServer;
	import org.apache.thrift.server.TServer.Args;
	import org.apache.thrift.server.TSimpleServer;
	import org.apache.thrift.transport.TServerSocket;
	import org.apache.thrift.transport.TServerTransport;
	
	public class JavaServer {
	
	  public static CalcHandler handler;
	
	  public static Calc.Processor processor;
	
	  public static void main(String [] args) {
	    try {
	      handler = new CalcHandler();
	      processor = new Calc.Processor(handler);
	
	      TServerTransport serverTransport = new TServerSocket(9090);
	      TServer server = new TSimpleServer(new Args(serverTransport).processor(processor));
	      System.out.println("Starting the simple server...");
	      server.serve();
	      
	    } catch (Exception x) {
	      x.printStackTrace();
	    }
	  }
	
	}


7.Server is ready now, we can run the JavaServer.java to start the server.

8.Since the server is ready, we need to build the nodejs client now.

9.When we enter the gen-nodejs folder , there are already two js files generated by the compiler. What we need to do is to add a new js file to act as a client. We call it index.js here.

index.js


	var thrift = require('thrift');
	var Calc = require('./Calc');
	var types = require('./Calc_types');
	
	
	var connection = thrift.createConnection("localhost", 9090);
	
	connection.on('error', function(err) {
	  console.log(err);
	});
	
	// Create a Calc client with the connection
	var client = thrift.createClient(Calc, connection);
	
	client.add(1,1, function(err, response) {
	  console.log("1+1=" + response);
	});
	
	var mes = new types.Message();
	mes.mes = 'world';
	client.hello(mes, function(err, response) {
	  console.log(response.mes);
	  connection.end();
	});

10.Ok, we got our client now , before running this client, we have to do one more thing : npm install thrift (Actually in case of some unknown reasons, I hava already commited the node_modules with the code, so you do not need to run this npm install thrift). now if you try node index.js you will see the result of the communication.

Have fun!

Plus: in fect, if you visit the thrift apache site, you can find Tutorial, too. But the code http://thrift.apache.org/tutorial/nodejs shows need some fixes to run.

remove

var ThriftTransports = require('thrift/transport');
var ThriftProtocols = require('thrift/protocol');

and change

transport = ThriftTransports.TBufferedTransport()
protocol = ThriftProtocols.TBinaryProtocol()

to

transport = thrift.TBufferedTransport()
protocol = thrift.TBinaryProtocol()