org.apache.thrift.protocol.TBinaryProtocol.Factory Java Examples

The following examples show how to use org.apache.thrift.protocol.TBinaryProtocol.Factory. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ThriftTest.java    From java-specialagent with Apache License 2.0 6 votes vote down vote up
private void startNewThreadPoolServer() throws Exception {
  final TServerTransport transport = new TServerSocket(port);
  final TProtocolFactory protocolFactory = new TBinaryProtocol.Factory();
  // TTransportFactory transportFactory = new TFramedTransport.Factory();

  final CustomHandler customHandler = new CustomHandler();
  final TProcessor customProcessor = new CustomService.Processor<CustomService.Iface>(customHandler);

  final TThreadPoolServer.Args args = new TThreadPoolServer.Args(transport)
    .processorFactory(new TProcessorFactory(customProcessor))
    .protocolFactory(protocolFactory)
    // .transportFactory(transportFactory)
    .minWorkerThreads(5)
    // .executorService(Executors.newCachedThreadPool())
    .maxWorkerThreads(10);

  server = new TThreadPoolServer(args);
  new Thread(new Runnable() {
    @Override
    public void run() {
      server.serve();
    }
  }).start();
}
 
Example #2
Source File: rpcServer.java    From leaf-snowflake with Apache License 2.0 6 votes vote down vote up
public static void startRPCServer(leafServer leafserver , String ip , int port) throws Exception
{
	ServerSocket serverSocket = new ServerSocket(port,10000, InetAddress.getByName(ip));

	TServerSocket serverTransport = new TServerSocket(serverSocket);

	//设置协议工厂为TBinaryProtocolFactory
	Factory proFactory = new TBinaryProtocol.Factory();
	//关联处理器leafrpc的实现
	TProcessor processor = new leafrpc.Processor<leafrpc.Iface>(new RPCService(leafserver));
	TThreadPoolServer.Args args2 = new TThreadPoolServer.Args(serverTransport);
	args2.processor(processor);
	args2.protocolFactory(proFactory);
	TServer server = new TThreadPoolServer(args2);
	LOG.info("leaf RPCServer(type:TThreadPoolServer) start at ip:port : "+ ip +":" + port );
	server.serve();
}
 
Example #3
Source File: rpcServer.java    From leaf-snowflake with Apache License 2.0 6 votes vote down vote up
public static void startRPCServer2(leafServer leafserver , String ip , int port) throws Exception
{
	//关联处理器leafrpc的实现
	TProcessor processor = new leafrpc.Processor<leafrpc.Iface>(new RPCService(leafserver));
	//传输通道,非阻塞模式
	InetSocketAddress address = new InetSocketAddress(InetAddress.getByName(ip),port);
	TNonblockingServerSocket serverTransport = new TNonblockingServerSocket(address,10000);
	//多线程半同步半异步
	TThreadedSelectorServer.Args tArgs = new TThreadedSelectorServer.Args(serverTransport);
	tArgs.processor(processor);
	//二进制协议
	tArgs.protocolFactory(new TBinaryProtocol.Factory());
	//多线程半同步半异步的服务模型
	TServer server = new TThreadedSelectorServer(tArgs);
	LOG.info("leaf RPCServer(type:TThreadedSelectorServer) start at ip:port : "+ ip +":" + port );
	server.serve();
}
 
Example #4
Source File: ThriftTest.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
@Test
public void async() throws Exception {
  TestUtil.setGlobalTracer(tracer);

  startAsyncServer();

  final Factory protocolFactory = new Factory();
  final TNonblockingTransport transport = new TNonblockingSocket("localhost", port);
  final TAsyncClientManager clientManager = new TAsyncClientManager();
  final AsyncClient asyncClient = new AsyncClient(protocolFactory, clientManager, transport);
  final AtomicInteger counter = new AtomicInteger();
  asyncClient.say("Async", "World", new AsyncMethodCallback<String>() {
    @Override
    public void onComplete(final String response) {
      assertEquals("Say Async World", response);
      assertNotNull(GlobalTracer.get().activeSpan());
      counter.incrementAndGet();
    }

    @Override
    public void onError(final Exception exception) {
      exception.printStackTrace();
    }
  });

  await().atMost(15, TimeUnit.SECONDS).until(TestUtil.reportedSpansSize(tracer), equalTo(2));
  assertEquals(1, counter.get());

  final List<MockSpan> spans = tracer.finishedSpans();
  assertEquals(2, spans.size());

  assertNull(tracer.activeSpan());
  verify(tracer, times(2)).buildSpan(anyString());
  verify(tracer, times(1)).inject(any(SpanContext.class), any(Format.class), any());
}
 
Example #5
Source File: ThriftTest.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
@Test
public void asyncWithoutArgs() throws Exception {
  TestUtil.setGlobalTracer(tracer);

  startAsyncServer();

  final Factory protocolFactory = new Factory();

  final TNonblockingTransport transport = new TNonblockingSocket("localhost", port);
  final TAsyncClientManager clientManager = new TAsyncClientManager();
  final AsyncClient asyncClient = new AsyncClient(protocolFactory, clientManager, transport);
  final AtomicInteger counter = new AtomicInteger();
  asyncClient.withoutArgs(new AsyncMethodCallback<String>() {
    @Override
    public void onComplete(final String response) {
      assertEquals("no args", response);
      assertNotNull(GlobalTracer.get().activeSpan());
      counter.incrementAndGet();
    }

    @Override
    public void onError(final Exception exception) {
      exception.printStackTrace();
    }
  });

  await().atMost(15, TimeUnit.SECONDS).until(TestUtil.reportedSpansSize(tracer), equalTo(2));
  assertEquals(1, counter.get());

  final List<MockSpan> spans = tracer.finishedSpans();
  assertEquals(2, spans.size());

  assertNull(tracer.activeSpan());
  verify(tracer, times(2)).buildSpan(anyString());
  verify(tracer, times(1)).inject(any(SpanContext.class), any(Format.class), any());
}
 
Example #6
Source File: ThriftTest.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
@Test
public void asyncMany() throws Exception {
  TestUtil.setGlobalTracer(tracer);

  startAsyncServer();

  final AtomicInteger counter = new AtomicInteger();
  for (int i = 0; i < 4; ++i) {
    final Factory protocolFactory = new Factory();
    final TNonblockingTransport transport = new TNonblockingSocket("localhost", port);
    final TAsyncClientManager clientManager = new TAsyncClientManager();
    final AsyncClient asyncClient = new AsyncClient(protocolFactory, clientManager, transport);
    asyncClient.withDelay(1, new AsyncMethodCallback<String>() {
      @Override
      public void onComplete(final String response) {
        assertEquals("delay 1", response);
        assertNotNull(GlobalTracer.get().activeSpan());
        counter.incrementAndGet();
      }

      @Override
      public void onError(final Exception exception) {
        exception.printStackTrace();
      }
    });
  }

  await().atMost(15, TimeUnit.SECONDS).until(TestUtil.reportedSpansSize(tracer), equalTo(8));
  assertEquals(4, counter.get());

  final List<MockSpan> spans = tracer.finishedSpans();
  assertEquals(8, spans.size());

  assertNull(tracer.activeSpan());
  verify(tracer, times(8)).buildSpan(anyString());
  verify(tracer, times(4)).inject(any(SpanContext.class), any(Format.class), any());
}
 
Example #7
Source File: ThriftTest.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
@Test
public void oneWayAsync() throws Exception {
  TestUtil.setGlobalTracer(tracer);

  startAsyncServer();

  final Factory protocolFactory = new Factory();
  final TNonblockingTransport transport = new TNonblockingSocket("localhost", port);
  final TAsyncClientManager clientManager = new TAsyncClientManager();
  final AsyncClient asyncClient = new AsyncClient(protocolFactory, clientManager, transport);
  final AtomicInteger counter = new AtomicInteger();
  asyncClient.oneWay(new AsyncMethodCallback<Void>() {
    @Override
    public void onComplete(final Void response) {
      assertNotNull(GlobalTracer.get().activeSpan());
      counter.incrementAndGet();
    }

    @Override
    public void onError(final Exception exception) {
      exception.printStackTrace();
    }
  });

  await().atMost(15, TimeUnit.SECONDS).until(TestUtil.reportedSpansSize(tracer), equalTo(2));
  assertEquals(1, counter.get());

  final List<MockSpan> spans = tracer.finishedSpans();
  assertEquals(2, spans.size());

  assertNull(tracer.activeSpan());
  verify(tracer, times(2)).buildSpan(anyString());
  verify(tracer, times(1)).inject(any(SpanContext.class), any(Format.class), any());
}
 
Example #8
Source File: TestApacheThriftMethodInvoker.java    From drift with Apache License 2.0 5 votes vote down vote up
private static int testProcessor(TProcessor processor, List<ToIntFunction<HostAndPort>> clients)
        throws Exception
{
    try (TServerSocket serverTransport = new TServerSocket(0)) {
        TProtocolFactory protocolFactory = new Factory();
        TTransportFactory transportFactory = new TFramedTransport.Factory();
        TServer server = new TSimpleServer(new Args(serverTransport)
                .protocolFactory(protocolFactory)
                .transportFactory(transportFactory)
                .processor(processor));

        Thread serverThread = new Thread(server::serve);
        try {
            serverThread.start();

            int localPort = serverTransport.getServerSocket().getLocalPort();
            HostAndPort address = HostAndPort.fromParts("localhost", localPort);

            int sum = 0;
            for (ToIntFunction<HostAndPort> client : clients) {
                sum += client.applyAsInt(address);
            }
            return sum;
        }
        finally {
            server.stop();
            serverThread.interrupt();
        }
    }
}
 
Example #9
Source File: rpcServer.java    From leaf-snowflake with Apache License 2.0 5 votes vote down vote up
public static void startRPCServer3(leafServer leafserver , String ip , int port) throws Exception
{
	TProcessor processor = new leafrpc.Processor<leafrpc.Iface>(new RPCService(leafserver));
	//传输通道,非阻塞模式
	InetSocketAddress address = new InetSocketAddress(InetAddress.getByName(ip),port);
	TNonblockingServerSocket serverTransport = new TNonblockingServerSocket(address,10000);
	TNonblockingServer.Args args = new TNonblockingServer.Args(serverTransport);
	args.protocolFactory(new TBinaryProtocol.Factory());
	args.transportFactory(new TFramedTransport.Factory());
	args.processorFactory(new TProcessorFactory(processor));
	TServer server = new TNonblockingServer(args);
	LOG.info("leaf RPCServer(type:TNonblockingServerSocket) start at ip:port : "+ ip +":" + port );
	server.serve();
}
 
Example #10
Source File: rpcServer.java    From leaf-snowflake with Apache License 2.0 5 votes vote down vote up
public static void startRPCServer4(leafServer leafserver , String ip , int port) throws Exception
{
	TProcessor processor = new leafrpc.Processor<leafrpc.Iface>(new RPCService(leafserver));
	//传输通道,非阻塞模式
	InetSocketAddress address = new InetSocketAddress(InetAddress.getByName(ip),port);
	TNonblockingServerSocket serverTransport = new TNonblockingServerSocket(address,10000);
	THsHaServer.Args  args = new THsHaServer.Args(serverTransport);
	args.processor(processor);
	args.protocolFactory(new TBinaryProtocol.Factory());
	args.transportFactory(new TFramedTransport.Factory());
	TServer server = new THsHaServer(args);
	LOG.info("leaf RPCServer(type:THsHaServer) start at ip:port : "+ ip +":" + port );
	server.serve();
}
 
Example #11
Source File: ExampleServer.java    From Thrift-Connection-Pool with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
	try {
		int port = 9119;
		TServerTransport serverTransport = new TServerSocket(port);
		Factory proFactory = new TBinaryProtocol.Factory();
		Processor<Iface> processor = new Example.Processor<Example.Iface>(new Example.Iface() {

			@Override
			public void pong() throws TException {
				System.out.println("pong");
			}

			@Override
			public void ping() throws TException {
				System.out.println("ping");
			}
		});
		Args thriftArgs = new Args(serverTransport);
		thriftArgs.processor(processor);
		thriftArgs.protocolFactory(proFactory);
		TServer tserver = new TThreadPoolServer(thriftArgs);
		System.out.println("启动监听:" + port);
		tserver.serve();
	} catch (TTransportException e) {
		e.printStackTrace();
	}
}
 
Example #12
Source File: TestCorruptScroogeRecords.java    From parquet-mr with Apache License 2.0 5 votes vote down vote up
@Override
protected void assertEqualsExcepted(List<org.apache.parquet.thrift.test.compat.StructWithUnionV2> expected, List<Object> found) throws Exception {
  List<StructWithUnionV2> scroogeExpected = new ArrayList<StructWithUnionV2>();
  for (org.apache.parquet.thrift.test.compat.StructWithUnionV2 tbase : expected) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    TProtocol out = new Factory().getProtocol(new TIOStreamTransport(baos));
    tbase.write(out);
    TProtocol in = new Factory().getProtocol(new TIOStreamTransport(new ByteArrayInputStream(baos.toByteArray())));
    scroogeExpected.add(StructWithUnionV2$.MODULE$.decode(in));
  }
  assertEquals(scroogeExpected, found);
 }
 
Example #13
Source File: BasicAbstractTest.java    From Thrift-Connection-Pool with Apache License 2.0 4 votes vote down vote up
protected ThriftServerInfo startServer() throws Throwable {
	// 获取一个监听端口
	final int port = choseListenPort();
	ThriftServerInfo serverInfo = new ThriftServerInfo(LOACLHOST, port);
	final AtomicReference<Throwable> ex = new AtomicReference<Throwable>();

	Thread runner = new Thread("thrift-server-starter") {
		@Override
		public void run() {
			try {
				TServerTransport serverTransport = new TServerSocket(port);
				Factory proFactory = new TBinaryProtocol.Factory();
				Processor<Iface> processor = new Example.Processor<Example.Iface>(new Example.Iface() {

					@Override
					public void pong() throws TException {
						logger.info("pong");
					}

					@Override
					public void ping() throws TException {
						logger.info("ping");
					}
				});
				Args thriftArgs = new Args(serverTransport);
				thriftArgs.processor(processor);
				thriftArgs.protocolFactory(proFactory);
				TServer tserver = new TThreadPoolServer(thriftArgs);
				servers.add(tserver);
				logger.info("启动测试服务监听:" + port);
				tserver.serve();
			} catch (TTransportException e) {
				logger.error("thrift服务器启动失败", e);
				ex.set(e);
			}
		}
	};

	runner.start();

	Throwable throwable = ex.get();
	if (throwable != null) {
		throw throwable;
	}
	// 等待服务器启动
	Thread.sleep(1000);
	return serverInfo;
}
 
Example #14
Source File: BasicAbstractTest.java    From Thrift-Connection-Pool with Apache License 2.0 4 votes vote down vote up
protected ThriftServerInfo startMulitServiceServer() throws Throwable {
	// 获取一个监听端口
	final int port = choseListenPort();
	ThriftServerInfo serverInfo = new ThriftServerInfo(LOACLHOST, port);
	final AtomicReference<Throwable> ex = new AtomicReference<Throwable>();
	// TODO
	Thread runner = new Thread("thrift-server-starter") {
		@Override
		public void run() {
			try {
				TMultiplexedProcessor processor = new TMultiplexedProcessor();
				TServerTransport serverTransport = new TServerSocket(port);
				Factory proFactory = new TBinaryProtocol.Factory();

				processor.registerProcessor("example", new Example.Processor<Example.Iface>(new Example.Iface() {

					@Override
					public void pong() throws TException {
						logger.info("example pong");
					}

					@Override
					public void ping() throws TException {
						logger.info("example ping");
					}
				}));

				processor.registerProcessor("other", new Other.Processor<Other.Iface>(new Other.Iface() {

					@Override
					public void pong() throws TException {
						logger.info("other pong");
					}

					@Override
					public void ping() throws TException {
						logger.info("other ping");
					}
				}));
				Args thriftArgs = new Args(serverTransport);
				thriftArgs.processor(processor);
				thriftArgs.protocolFactory(proFactory);
				TServer tserver = new TThreadPoolServer(thriftArgs);
				servers.add(tserver);
				logger.info("启动测试服务监听:" + port);
				tserver.serve();
			} catch (TTransportException e) {
				logger.error("thrift服务器启动失败", e);
				ex.set(e);
			}
		}
	};

	runner.start();

	Throwable throwable = ex.get();
	if (throwable != null) {
		throw throwable;
	}
	// 等待服务器启动
	Thread.sleep(1000);
	return serverInfo;
}