@Override protected FrameBuffer createFrameBuffer(TNonblockingTransport trans, SelectionKey selectionKey, AbstractSelectThread selectThread) { TrackingFrameBuffer frameBuffer = new TrackingFrameBuffer(trans, selectionKey, selectThread); if (trans instanceof TNonblockingSocket) { try { SocketChannel socketChannel = ((TNonblockingSocket) trans).getSocketChannel(); InetAddress addr = ((InetSocketAddress) socketChannel.getRemoteAddress()).getAddress(); clientAddresses.put(frameBuffer.getInputFramedTransport(), addr); } catch (IOException e) { log.warn("Exception while tracking client address", e); clientAddresses.remove(frameBuffer.getInputFramedTransport()); } } else { log.warn("Unknown TNonblockingTransport instance: {}", trans.getClass().getName()); clientAddresses.remove(frameBuffer.getInputFramedTransport()); } return frameBuffer; }
@Test public void testAysncServiceImpl() { int serverPort = 49001; TProcessor p = new ServiceProcessor(new TestThriftServiceImpl1()); thriftServerConfiguration.setProcessorFactory(new TProcessorFactory(p)); Factory factory = new GeneralFactory(thriftServerConfiguration); ThriftServer thriftServer = factory.getThriftServer(serverPort, new TestThriftServiceImpl1()); thriftServer.run(); try { AsyncService service = factory.getAsyncService(new TNonblockingSocket(LOCAL_HOST, serverPort)); Thread.sleep(500); TestCallback1 callback = new TestCallback1(); service.get(testString1, callback); Thread.sleep(1000); } catch (Exception e) { fail(); } finally { thriftServer.stop(); } }
private boolean validate(Object target, Object[] args) { if (!(target instanceof TNonblockingSocket)) { return false; } if (args.length != 3) { return false; } if (!(target instanceof SocketFieldAccessor)) { if (isDebug) { logger.debug("Invalid target object. Need field accessor({}).", SocketFieldAccessor.class.getName()); } return false; } if (!(target instanceof SocketAddressFieldAccessor)) { if (isDebug) { logger.debug("Invalid target object. Need field accessor({}).", SocketAddressFieldAccessor.class.getName()); } return false; } return true; }
protected TNonblockingSocket acceptImpl() throws TTransportException { if (serverSocket_ == null) { throw new TTransportException(TTransportException.NOT_OPEN, "No underlying server socket."); } try { SocketChannel socketChannel = serverSocketChannel.accept(); if (socketChannel == null) { return null; } TNonblockingSocket tsocket = new TNonblockingSocket(socketChannel); tsocket.setTimeout(0); // disabling client timeout tsocket.getSocketChannel().socket().setKeepAlive(true); tsocket.getSocketChannel().socket().setSendBufferSize(config.getSocketSendBufferBytes()); tsocket.getSocketChannel().socket().setReceiveBufferSize(config.getSocketRecvBufferBytes()); return tsocket; } catch (IOException iox) { throw new TTransportException(iox); } }
@Override public void open() { try { //异步调用管理器 this.clientManager = new TAsyncClientManager(); //设置传输通道,调用非阻塞IO。 this.transport = new TNonblockingSocket(this.serverInfo.getIp(), this.serverInfo.getPort(), 1000); } catch (Exception e) { log.error("create AsyncTrpcClient:" + this.serverInfo + " error", e); throw new TRpcException("create AsyncTrpcClient:" + this.serverInfo + " error", e); } }
@Test public void testAysncMultiplexedServiceImpl() { int serverPort = 49002; Map<String, TProcessor> processorMap = new HashMap<>(); processorMap.put("testAysncService1", new ServiceProcessor(new TestThriftServiceImpl1())); processorMap.put("testAysncService2", new ServiceProcessor(new TestThriftServiceImpl2())); MultiplexedProcessor p = new MultiplexedProcessor(processorMap); thriftServerConfiguration.setProcessorFactory(new TProcessorFactory(p)); Factory factory = new GeneralFactory(thriftServerConfiguration); ThriftServer thriftServer = factory.getThriftServer("testAysncMultiplexedService", serverPort, p); thriftServer.run(); try { Thread.sleep(500); AsyncService service1 = factory.getAsyncService(new TNonblockingSocket(LOCAL_HOST, serverPort), "testAysncService1"); TestCallback1 callback1 = new TestCallback1(); service1.get(testString1, callback1); AsyncService service2 = factory.getAsyncService(new TNonblockingSocket(LOCAL_HOST, serverPort), "testAysncService2"); TestCallback2 callback2 = new TestCallback2(); service2.get(testString2, callback2); Thread.sleep(1000); } catch (Exception e) { fail(); } finally { thriftServer.stop(); } }
@Test public void testAysncDefaultThriftServerImpl() { int serverPort = 39004; TProcessor p = new ThriftSimpleService.Processor<Iface>(new ThriftSimpleServiceImpl()); ThriftServerConfiguration thriftServerConfiguration = new ThriftServerConfiguration(); thriftServerConfiguration.setProtocolFactory(new TCompactProtocol.Factory()); thriftServerConfiguration.setProcessorFactory(new TProcessorFactory(p)); thriftServerConfiguration.setServerArgsAspect(new ServerArgsAspect() { @Override public TThreadPoolServer.Args TThreadPoolServerArgsAspect(TThreadPoolServer.Args args) { args.stopTimeoutVal = 1; return args; } }); Factory factory = new GeneralFactory(thriftServerConfiguration); ThriftServer thriftServer = factory.getThriftServer(serverName, serverPort, p); thriftServer.run(); try { ThriftSimpleService.AsyncClient thriftClient = new ThriftSimpleService.AsyncClient( new TCompactProtocol.Factory(), new TAsyncClientManager(), new TNonblockingSocket(LOCAL_HOST, serverPort)); Thread.sleep(500); TestCallback callback = new TestCallback(); thriftClient.get(testString, callback); Thread.sleep(1000); } catch (Exception e) { fail(); } finally { thriftServer.stop(); } }
@Override public T makeObject(InetSocketAddress socket) throws Exception { TNonblockingTransport nbTr = new TNonblockingSocket( socket.getAddress().getHostAddress(), socket.getPort()); TProtocolFactory factory = new TBinaryProtocol.Factory(); T client = maker.create(nbTr, clientManager, factory); transports.put(client, nbTr); return client; }
@Override protected boolean requestInvoke(FrameBuffer frameBuffer) { TNonblockingSocket socket = (TNonblockingSocket)((CustomFrameBuffer)frameBuffer).getTransport(); ThriftSessionManager.instance.setCurrentSocket(socket.getSocketChannel().socket().getRemoteSocketAddress()); frameBuffer.invoke(); return true; }
@Override @SuppressWarnings("resource") protected boolean requestInvoke(FrameBuffer frameBuffer) { TNonblockingSocket socket = (TNonblockingSocket)((CustomFrameBuffer)frameBuffer).getTransport(); ThriftSessionManager.instance.setCurrentSocket(socket.getSocketChannel().socket().getRemoteSocketAddress()); frameBuffer.invoke(); return true; }
public void run() { TNonblockingSocket socket = (TNonblockingSocket) frameBuffer.trans_; ThriftSessionManager.instance.setCurrentSocket(socket.getSocketChannel().socket().getRemoteSocketAddress()); frameBuffer.invoke(); // this is how we let the same selector thread change the selection type. thread.requestSelectInterestChange(frameBuffer); }
private void cleanupSelectionkey(SelectionKey key) { FrameBuffer buffer = (FrameBuffer) key.attachment(); if (buffer != null) { buffer.close(); TNonblockingSocket socket = (TNonblockingSocket) buffer.trans_; if (socket != null) ThriftSessionManager.instance.connectionComplete(socket.getSocketChannel().socket().getRemoteSocketAddress()); } key.cancel(); }
@Override protected boolean requestInvoke(FrameBuffer frameBuffer) { TNonblockingSocket socket = (TNonblockingSocket) frameBuffer.trans_; ThriftSessionManager.instance.setCurrentSocket(socket.getSocketChannel().socket().getRemoteSocketAddress()); frameBuffer.invoke(); return true; }
@Override public void after(Object target, Object[] args, Object result, Throwable throwable) { if (isDebug) { logger.afterInterceptor(target, args, result, throwable); } if (validate(target, args)) { Socket socket = ((TNonblockingSocket)target).getSocketChannel().socket(); ((SocketFieldAccessor)target)._$PINPOINT$_setSocket(socket); if (args[2] instanceof SocketAddress) { SocketAddress socketAddress = (SocketAddress)args[2]; ((SocketAddressFieldAccessor)target)._$PINPOINT$_setSocketAddress(socketAddress); } } }
public void run() { TNonblockingSocket socket = (TNonblockingSocket) frameBuffer.trans_; SocketSessionManagementService.remoteSocket.set(socket.getSocketChannel().socket().getRemoteSocketAddress()); frameBuffer.invoke(); // this is how we let the same selector thread change the selection type. thread.requestSelectInterestChange(frameBuffer); }
@Override protected boolean requestInvoke(FrameBuffer frameBuffer) { TNonblockingSocket socket = (TNonblockingSocket) frameBuffer.trans_; SocketSessionManagementService.remoteSocket.set(socket.getSocketChannel().socket().getRemoteSocketAddress()); frameBuffer.invoke(); return true; }
@Test public void test_AsyncClient() throws Throwable { Random rnd = new Random(System.nanoTime()); TProtocolFactory[] protfacs = new TProtocolFactory[] { new TCompactProtocol.Factory(), new TBinaryProtocol.Factory(), new TJSONProtocol.Factory(), new TSimpleJSONProtocol.Factory(TCalculator.Iface.class, false) }; TProtocolFactory protocolFactory = protfacs[rnd.nextInt(protfacs.length)]; System.out.println("protocolFactory: " + protocolFactory); TAsyncClientManager clientManager = new TAsyncClientManager(); TNonblockingTransport transport = new TNonblockingSocket(HOST, PORT); TCalculator.AsyncClient client = new TCalculator.AsyncClient(protocolFactory, clientManager, transport); final int num1 = rnd.nextInt(Integer.MAX_VALUE / 2 - 1); final int num2 = rnd.nextInt(Integer.MAX_VALUE / 2 - 1); final CountDownLatch latch = new CountDownLatch(1); final Throwable[] exceptions = new Throwable[1]; AsyncMethodCallback<TCalculator.AsyncClient.add_call> resultHandler = new AsyncMethodCallback<TCalculator.AsyncClient.add_call>() { @Override public void onComplete(TCalculator.AsyncClient.add_call response) { System.out.println("onComplete!"); try { int result = response.getResult(); Assert.assertEquals(num1 + num2, result); } catch (Throwable e) { exceptions[0] = e; } finally { latch.countDown(); } } @Override public void onError(Exception exception) { System.err.println("onError!"); exception.printStackTrace(); latch.countDown(); } }; client.add(num1, num2, resultHandler); latch.await(); transport.close(); if (exceptions[0] != null) { throw exceptions[0]; } }
@Override protected void beforeInvoke(Message buffer) { TNonblockingSocket socket = (TNonblockingSocket) buffer.transport; ThriftSessionManager.instance.setCurrentSocket(socket.getSocketChannel().socket().getRemoteSocketAddress()); }
public void beforeClose(Message buffer) { TNonblockingSocket socket = (TNonblockingSocket) buffer.transport; ThriftSessionManager.instance.connectionComplete(socket.getSocketChannel().socket().getRemoteSocketAddress()); }
public static void main(String[] args) throws IOException, InterruptedException, TException { //Async client and I/O stack setup TNonblockingSocket trans_ep = new TNonblockingSocket("localhost", 9090); TAsyncClientManager client_man = new TAsyncClientManager(); TradeReporting.TradeHistory.AsyncClient client = new TradeReporting.TradeHistory.AsyncClient(new TBinaryProtocol.Factory(), client_man, trans_ep); //get_last_sale() async callback handler WaitableCallback<TradeReport> wc = new WaitableCallback<TradeReport>() { @Override public void onComplete(TradeReport tr) { try { System.out.println("[Client] received [" + tr.seq_num + "] " + tr.symbol + " : " + tr.size + " @ " + tr.price); } finally { complete(); } } }; //Make async calls wc.reset(); client.get_last_sale("IBM", wc); System.out.println("[Client] get_last_sale() executing asynch..."); wc.wait(500); wc.reset(); client.get_last_sale("F", wc); wc.wait(25000); //Make an async call which will time out client.setTimeout(1000); wc.reset(); client.get_last_sale("GE", wc); wc.wait(5000); //Shutdown async client manager and close network socket client_man.stop(); trans_ep.close(); }