thrift servlet

阅读更多

 

Thrift通常以独立服务存在,也支持HTTP协议,以servlet方式在Tomcat中运行。

 

一. 服务端Servlet

实现比较简单,只需实现TExtensibleServlet,并在getProcessor()中填充实现类。

/**
 * Thrift servlet
 */
@WebServlet(name="thrifttest",value="/thrifttest")
public class ThriftService extends TExtensibleServlet {
	private static final long serialVersionUID = 1L;

	@Override
	protected TProtocolFactory getInProtocolFactory() {
		TProtocolFactory factory = new TCompactProtocol.Factory();
		return factory;
	}

	@Override
	protected TProtocolFactory getOutProtocolFactory() {
		TProtocolFactory factory = new TCompactProtocol.Factory();
		return factory;
	}

	@Override
	protected TProcessor getProcessor() {
		// 接口实现类
		ThriftServiceImpl impl = new ThriftServiceImpl();

		// 返回处理器
		TProcessor tProcesser = new SimpleThriftService.Processor(impl); 
		return tProcesser;
	}
}

 

二. 客户端

/**
 * Http thrift client
 */
public static void httpClient() {  
	String url = "http://host:8080/servlet3/thrifttest";  
	try {
		TTransport transport = new THttpClient(url); 	         
		TProtocol protocol = new TCompactProtocol(transport); // HTTP通信协议     
		SimpleThriftService.Client client = new SimpleThriftService.Client(protocol);

		transport.open();  
		int val = client.getInt(10); 	// 调用方法
		System.out.println( "Val: " + val );

		transport.close();  
	} catch (TException e) {
		e.printStackTrace();
	}  
} 

 

三. 协议分析

thrift servlet_第1张图片 

 

 

 

 

 

 

 

 

 

 

  • thrift servlet_第2张图片
  • 大小: 72.8 KB
  • 查看图片附件

你可能感兴趣的:(thrift,servlet)