Thrift 异步调用

来源:互联网 发布:大数据发展趋势 ppt 编辑:程序博客网 时间:2024/06/10 16:34

服务端

import org.apache.thrift.TProcessor;import org.apache.thrift.protocol.TCompactProtocol;import org.apache.thrift.server.TNonblockingServer;import org.apache.thrift.server.TServer;import org.apache.thrift.transport.TFramedTransport;import org.apache.thrift.transport.TNonblockingServerSocket;import org.apache.thrift.transport.TTransportException;import com.whr.rpc.service.MessageForwardsService;public class MessageForwardsServer {    public static MessageForwardsRpcInterface handler;    @SuppressWarnings("rawtypes")    public static MessageForwardsService.Processor processor;    public static void start() {                try {            System.out.println("async TNonblockingServer start ....");            final TProcessor tprocessor = new MessageForwardsService.Processor<MessageForwardsService.Iface>(                    new MessageForwardsRpcInterface());            Runnable simple = new Runnable() {                public void run() {                    simple(tprocessor);                }            };            new Thread(simple).start();        } catch (Exception e) {            System.out.println("Server start error!!!");            e.printStackTrace();        }    }//  /**//   * RPC 服务端//   * @param processor//   */    public static void simple(TProcessor tprocessor)  {        TNonblockingServerSocket tnbSocketTransport;        try {            tnbSocketTransport = new TNonblockingServerSocket(9090);            TNonblockingServer.Args tnbArgs = new TNonblockingServer.Args(                    tnbSocketTransport);            tnbArgs.processor(tprocessor);            tnbArgs.transportFactory(new TFramedTransport.Factory());            tnbArgs.protocolFactory(new TCompactProtocol.Factory());            // 使用非阻塞式IO,服务端和客户端需要指定TFramedTransport数据传输的方式            TServer server = new TNonblockingServer(tnbArgs);            server.serve();        } catch (TTransportException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }    }}

客户端

public class ControlCommand {    public static void main( String[] args )    {        test("192.168.1.3");    }    public static void test(String ip){        TTransport transport = null;        try {            transport = new TFramedTransport(new TSocket(ip,9090, 3000));            // 协议要和服务端一致            TProtocol protocol = new TCompactProtocol(transport);            MessageForwardsService.Client client = new MessageForwardsService.Client(                    protocol);            transport.open();            String result = client.getAllChannels();            System.out.println("Thrify client result =: " + result);            transport.close();        } catch (TTransportException e) {            e.printStackTrace();        } catch (TException e) {            e.printStackTrace();        } finally {            if (null != transport) {                transport.close();            }        }    }}
原创粉丝点击