namespace java com.thrift.demo.service
service helloservice{
string sayhello(1:string username)
}
编译
编译之后会生成类helloservice。
thrift -gen java helloservice.thrift
编写实现类
helloserviceimpl.java
public class helloserviceimpl implements helloservice.iface {
@override
public string sayhello(string username) throws texception {
return "hello thrift service : " + username;
}
}
编写服务端代码
public class helloserver {
public static final int server_port = 8090;
public void startserver() {
try {
system.out.println("helloservice tsimpleserver start ....");
tprocessor tprocessor = new helloservice.processor<helloservice.iface>(new helloserviceimpl());
// 简单的单线程服务模型,一般用于测试
tserversocket servertransport = new tserversocket(server_port);
tserver.args targs = new tserver.args(servertransport);
targs.processor(tprocessor);
targs.protocolfactory(new tbinaryprotocol.factory());
tserver server = new tsimpleserver(targs);
server.serve();
} catch (exception e) {
system.out.println("server start error!!!");
e.printstacktrace();
}
}
public static void main(string[] args) {
helloserver server = new helloserver();
server.startserver();
}
}
编写客户端代码
public class helloclient {
public static final string server_ip = "localhost";
public static final int server_port = 8090;
public static final int timeout = 30000;
public void startclient(string username) {
ttransport transport = null;
try {
transport = new tsocket(server_ip, server_port, timeout);
// 协议要和服务端一致
tprotocol protocol = new tbinaryprotocol(transport);
helloservice.client client = new helloservice.client(protocol);
transport.open();
string result = client.sayhello(username);
system.out.println("thrify client result =: " + result);
} catch (ttransportexception e) {
e.printstacktrace();
} catch (texception e) {
e.printstacktrace();
} finally {
if (null != transport) {
transport.close();
}
}
}
public static void main(string[] args) {
helloclient client = new helloclient();
client.startclient("michael");
}
}