在上一节Apache Thrift 初学小讲(二)【一个简单示例】中client端提到http类型的transport,但是并没有给出相应的服务端实现。
本节主要写一个transport为http的例子,以java为例,server端thrift提供了一个类TExtensibleServlet,只需要写一个servlet继承这个类,并实现以下抽象方法即可:
protected TProtocolFactory getInProtocolFactory();//in通信协议
protected TProtocolFactory getOutProtocolFactory();//out通信协议
protected TProcessor getProcessor();//具体的业务处理逻辑类
然后选择一个servlet容器比如tomcat发布这个servlet,最后client端的transport使用THttpClient即可。
服务端TestServlet.java:
import javax.servlet.annotation.WebServlet;
import org.apache.thrift.TProcessor;
import org.apache.thrift.protocol.TCompactProtocol;
import org.apache.thrift.protocol.TProtocolFactory;
import org.apache.thrift.server.TExtensibleServlet;
import thrift.test.ThriftTest;
@WebServlet("/TestServlet")
public class TestServlet extends TExtensibleServlet {
@Override
protected TProtocolFactory getInProtocolFactory() {
TProtocolFactory tProtocolFactory = new TCompactProtocol.Factory();
return tProtocolFactory;
}
@Override
protected TProtocolFactory getOutProtocolFactory() {
TProtocolFactory tProtocolFactory = new TCompactProtocol.Factory();
return tProtocolFactory;
}
@Override
protected TProcessor getProcessor() {
//具体的业务逻辑类,实现ThriftTest.thrift里的getUser接口
TestHandler testHandler = new TestHandler();
//ThriftTest.Processor是生成的服务端代码
ThriftTest.Processor testProcessor = new ThriftTest.Processor(testHandler);
return testProcessor;
}
}
客户端TestClient.java:
import org.apache.thrift.protocol.TCompactProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.THttpClient;
import org.apache.thrift.transport.TTransport;
import thrift.test.ThriftTest;
import thrift.test.User;
public class TestClient {
public static void main(String [] args) throws Exception {
String host = "localhost";
int port = 8080;
String url = "http://" + host + ":" + port + "/test/TestServlet";
TTransport transport = new THttpClient(url); //通信方式为http
TProtocol tProtocol = new TCompactProtocol(transport); //通信协议
//ThriftTest.Client是生成的客户端代码
ThriftTest.Client testClient = new ThriftTest.Client(tProtocol);
System.out.println("connect " + host + ":" + port);
transport.open();
User user = testClient.getUser(2); //getUser就是ThriftTest.thrift所定义的接口
System.out.println("名字:"+ user.getName());
transport.close();
}
}
启动tomcat,运行TestClient,结果:
connect localhost:8080
名字:另外一个烟火
工程文件结构:
附件ThriftServlet.rar是整个eclipse工程文件。