Thrift usually exists as an independent service, also supports the HTTP protocol, and runs in Tomcat as a servlet.
1. Server Servlet
The implementation is relatively simple, just implement TExtensibleServlet and fill in the implementation class in 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() { // interface implementation class ThriftServiceImpl impl = new ThriftServiceImpl(); // return handler TProcessor tProcesser = new SimpleThriftService.Processor<SimpleThriftService.Iface>(impl); return tProcesser; } }
2. Client
/** * 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 communication protocol SimpleThriftService.Client client = new SimpleThriftService.Client(protocol); transport.open(); int val = client.getInt(10); // call method System.out.println( "Val: " + val ); transport.close(); } catch (TException e) { e.printStackTrace (); } }
3. Protocol Analysis