使用thrift的流程:
1、下载thrift的exe,编写thrift接口文件,使用thrift --gen java + 文件名生成Java的接口文件,使用thrift --gen js:node +文件名
生成nodejs接口文件。接口文件PrintService.thrift如下:
namespace java com.huangshisheng
service Print {
bool println(1: string str)
}
2、Java编写服务端,需要下载thrift的依赖包,之后实现thrift接口。依赖的包如下:
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.apache.thrift</groupId>
<artifactId>libthrift</artifactId>
<version>0.9.3</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.5</version>
</dependency>
服务端代码如下:
public class Server implements Print.Iface {
public boolean println(String str) throws TException {
// TODO Auto-generated method stub
System.out.println(str);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
}
public static void main(String[] as) {
TNonblockingServerTransport serverTransport = null;
try {
serverTransport = new TNonblockingServerSocket(8888);
} catch (TTransportException e) {
e.printStackTrace();
}
//Server 为Hello接口的实现类
Print.Processor<Print.Iface> processor = new Print.Processor<Print.Iface>(
new Server());
Factory protFactory = new TBinaryProtocol.Factory(true, true);
TNonblockingServer.Args args = new TNonblockingServer.Args(
serverTransport);
args.processor(processor);
args.protocolFactory(protFactory);
TServer server = new TNonblockingServer(args);
System.out.println("Start server on port 19090 ...");
server.serve();
}
}
Java客户端代码如下:
public class Client {
public static void main(String[] args) {
long startTime = System.currentTimeMillis();
try {
TTransport transport = new TFramedTransport(new TSocket(
"localhost", 8888));
TBinaryProtocol protocol = new TBinaryProtocol(transport);
// TCompactProtocol protocol = new TCompactProtocol(transport);
Print.Client client = new Print.Client(protocol);
transport.open();
for (int i = 0; i < 1000; i++) {
System.out.println(client.println("login"));
}
transport.close();
} catch (TException x) {
x.printStackTrace();
}
long endTime = System.currentTimeMillis();
System.out.println(" 本次调用完成时间:" + (endTime - startTime));
}
}
3、将生成的nodejs的接口文件拷贝到nodejs项目下,nodejs请求服务的代码如下:
var Print = require('./gen-nodejs/Print'),
type = require('./gen-nodejs/PrintService_types'),
thrift = require('thrift');
var transport = thrift.TFramedTransport;
var protocol = thrift.TBinaryProtocol;
var connection = thrift.createConnection('localhost', 8888, {
transport: transport,
protocol: protocol
});
var client = thrift.createClient(Print, connection);
connection.on('error', function (err) {
console.log(err);
});
client.println("hello", function (err, result) {
console.log(result)
connection.end();
});
参考资料:
https://www.cnblogs.com/zfygiser/p/6651645.html