您的位置:首页 > 编程语言 > Java开发

Thrift java服务器与客户端示例 - john c - 博客园

2011-06-19 03:04 405 查看
Thrift java服务器与客户端示例 - john c - 博客园

Thrift java服务器与客户端示例

Posted on 2011-06-19 03:04 john c 阅读(3540) 评论(0) 编辑 收藏



简单的实现一个PING的功能

1.安装thrift

http://thrift.apache.org/download/

人人网镜像下载:

http://labs.renren.com/apache-mirror/thrift/0.6.1/thrift-0.6.1.exe

2.编写Thrift文件(定义接口,结构,异常等),保存为test.thrift

?
3.生成接口代码

把thrift-0.6.1.exe和test.thrift文件放在同一个目录,当然也可以把thrift-0.6.1.exe文件放进环境变量

进入DOS命令执行:thrift-0.6.1.exe --gen java test.thrift

生成文件 gen-java/net/johnc/thrift/Test.java

4.编写服务端接口实现类

在POM.xml文件加入以下依赖:

?
把生成的Test.java复制到项目下


package net.johnc.thrift;

import org.apache.thrift.TException;

public class TestImpl implements Test.Iface {

public void ping(int length) throws TException {
System.out.println("calling ping ,length=" + length);
}

}

5.编写启动服务代码


package net.johnc.thrift;

import net.johnc.thrift.Test.Processor;

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 Server {
public void startServer() {
try {

TServerSocket serverTransport = new TServerSocket(1234);

Test.Processor process = new Processor(new TestImpl());

Factory portFactory = new TBinaryProtocol.Factory(true, true);

Args args = new Args(serverTransport);
args.processor(process);
args.protocolFactory(portFactory);

TServer server = new TThreadPoolServer(args);
server.serve();
} catch (TTransportException e) {
e.printStackTrace();
}
}

public static void main(String[] args) {
Server server = new Server();
server.startServer();
}
}



6.编写客户端代码


package net.johnc.thrift;

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 Client {

public void startClient() {
TTransport transport;
try {
transport = new TSocket("localhost", 1234);
TProtocol protocol = new TBinaryProtocol(transport);
Test.Client client = new Test.Client(protocol);
transport.open();
client.ping(2012);
transport.close();
} catch (TTransportException e) {
e.printStackTrace();
} catch (TException e) {
e.printStackTrace();
}
}

public static void main(String[] args) {
Client client = new Client();
client.startClient();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: