namespace java com.example.thrift service ExampleService { double multiply(1: double arg1, 2: double arg2), void ping() } thrift --gen java example.thrift import com.example.thrift.ExampleService; import org.apache.thrift.TException; public class ExampleServiceImpl implements ExampleService.Iface { @Override public double multiply(double arg1, double arg2) throws TException { return arg1 * arg2; } @Override public void ping() throws TException { // do something } } import com.example.thrift.ExampleService; import com.example.thrift.ExampleServiceImpl; import org.apache.thrift.TProcessor; import org.apache.thrift.protocol.TBinaryProtocol; import org.apache.thrift.server.TServer; import org.apache.thrift.server.TThreadPoolServer; import org.apache.thrift.transport.TServerSocket; import org.apache.thrift.transport.TTransportException; public class Server { public void start() throws TTransportException { TProcessor processor = new ExampleService.Processor<>(new ExampleServiceImpl()); TServerSocket serverTransport = new TServerSocket(9090); TThreadPoolServer.Args serverArgs = new TThreadPoolServer.Args(serverTransport); serverArgs.processor(processor); serverArgs.protocolFactory(new TBinaryProtocol.Factory()); TServer server = new TThreadPoolServer(serverArgs); server.serve(); } public static void main(String[] args) throws TTransportException { Server server = new Server(); server.start(); } } import com.example.thrift.ExampleService; import org.apache.thrift.protocol.TBinaryProtocol; import org.apache.thrift.transport.TSocket; import org.apache.thrift.transport.TTransport; import org.apache.thrift.transport.TTransportException; public class Client { public static void main(String[] args) { try { TTransport transport = new TSocket("localhost", 9090); transport.open(); TBinaryProtocol protocol = new TBinaryProtocol(transport); ExampleService.Client client = new ExampleService.Client(protocol); double result = client.multiply(2.5, 3.2); System.out.println("Result: " + result); transport.close(); } catch (TTransportException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } }


上一篇:
下一篇:
切换中文