Apache Thrift 代码Demo,一个小栗子
注意 :
首先要安装thrift.exe thrift.exe的版本和jar包的版本最好保持一致.
代码结构
thrift文件
demoHello.java
service HelloWorldService{
string sayHello(1:string username)
}
使用Thrift.exe生成Service代码
1. 进入thrift文件所在的目录.
2. 使用命令行 thrift -gen java demoHello.thrift
这里需要说明一下 : -gen java 是命令参数 , 最后生成的Java代码包的路径 , 也是-gen java命名的…
3.然后将HelloWorldService.java 放在thrift目录下面就好了.. 将-gen java 删除.
4.最后是这个样子.
编写接口 ( HelloWorldImpl.java )
1. 该接口 实现 刚才生成的 Service代码 , 这里 implements 的时候 , 要注意一个'.Iface'
2. 所有业务的方法都是在接口实现中进行处理的.
import com.thrift.thrift_1.thrift.HelloWorldService;
import org.apache.thrift.TException;
public class HelloWorldImpl implements HelloWorldService.Iface {
public HelloWorldImpl() {
}
@Override
public String sayHello(String username) throws TException {
System.out.println("Server Hello : " + username);
return "Hi , " + username + " welcome to here";
}
}
import com.thrift.thrift_1.impl.HelloWorldImpl;
import com.thrift.thrift_1.thrift.HelloWorldService;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.server.TServer;
import org.apache.thrift.server.TSimpleServer;
import org.apache.thrift.transport.TServerSocket;
import java.io.IOException;
import java.net.ServerSocket;
/**
* 服务端
*/
public class HelloServerDemo {
public static final int SERVER_PORT = 9099;
public static void main(String[] args) {
try {
ServerSocket socket = new ServerSocket(SERVER_PORT);
TServerSocket serverTransport = new TServerSocket(socket);
HelloWorldService.Processor processor = new HelloWorldService.Processor(new HelloWorldImpl());
TServer.Args tArgs = new TServer.Args(serverTransport);
tArgs.processor(processor);
tArgs.protocolFactory(new TBinaryProtocol.Factory());
TServer server = new TSimpleServer(tArgs);
System.out.println("Running server....");
server.serve();
} catch (IOException e) {
e.printStackTrace();
}
}
}
import com.thrift.thrift_1.thrift.HelloWorldService;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;
public class HelloClientDemo {
public static final String SERVER_IP = "localhost";
public static final int SERVER_PORT = 9099;
public static final int TIMEOUT = 30000;
public static void main(String[] args) throws Exception{
startClient("CYX");
}
public static void startClient(String username) throws Exception{
TTransport transport = null;
try {
transport = new TSocket(SERVER_IP, SERVER_PORT, TIMEOUT);
TProtocol protocol = new TBinaryProtocol(transport);
HelloWorldService.Client client = new HelloWorldService.Client(protocol);
transport.open();
String result = client.sayHello(username);
System.out.println("Thrift client result = " + result);
} catch (Exception e) {
e.printStackTrace();
}
}
}
最后 , 运行先运行 Server 再运行 Client , Server 端就能收到 Client 发送的消息了 .