刚学习thrift,网上参考了一些资料,进行thrift入门例子的搭建。
0 . maven文件
<dependencies>
<dependency>
<groupId>org.apache.thrift</groupId>
<artifactId>libthrift</artifactId>
<version>0.10.0</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.6.1</version>
</dependency>
</dependencies>
1 . thrift文件编写 helloworld.thrift
namespace java com.thrift.demo
service HelloWorldService {
string sayHello(1:string name)
}
2 . thrift文件生成java文件
package com.thrift.demo;
@SuppressWarnings({"cast", "rawtypes", "serial", "unchecked", "unused"})
@javax.annotation.Generated(value = "Autogenerated by Thrift Compiler (0.10.0)", date = "2017-04-16")
public class HelloWorldService {
public interface Iface {
public String sayHello(String username) throws org.apache.thrift.TException;
}
}
其中生成的java文夹还有很多其他相关的方法,这里不再详细展示。
3 . 编写服务端
public class HelloServerDemo {
public static final int SERVER_PORT = 9099;
public void startServer() {
try {
System.out.println("server start ....");
TProcessor tprocessor = new HelloWorldService.Processor(new HelloWorldImpl());
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 happened error!!!");
e.printStackTrace();
}
}
/**
* @param args
*/
public static void main(String[] args) {
HelloServerDemo server = new HelloServerDemo();
server.startServer();
}
}
4 . 编写客户端
public class HelloClientDemo {
public static final String SERVER_IP = "localhost";
public static final int SERVER_PORT = 9099;
public static final int TIMEOUT = 30000;
/**
*
* @param userName
*/
public void startClient(String userName) {
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 remote call : " + result);
} catch (TTransportException e) {
e.printStackTrace();
} catch (TException e) {
e.printStackTrace();
} finally {
if (null != transport) {
transport.close();
}
}
}
/**
* @param args
*/
public static void main(String[] args) {
HelloClientDemo client = new HelloClientDemo();
client.startClient("THRIFT");
}
}
5 启动server和client
服务端启动控制台:
客户端调用及结果: