public static void main(String[] args) throws TTransportException, IOException, InterruptedException { TNonblockingServerSocket trans_svr = new TNonblockingServerSocket(9090); TMultiplexedProcessor proc = new TMultiplexedProcessor(); proc.registerProcessor("Message", new Message.Processor<>(new MessageHandler())); proc.registerProcessor("ServerTime", new ServerTime.Processor<>(new ServerTimeHandler())); TServer server = new TThreadedSelectorServer( new TThreadedSelectorServer.Args(trans_svr) .processor(proc) .protocolFactory(new TJSONProtocol.Factory()) .workerThreads(6) .selectorThreads(3)); Thread server_thread = new Thread(new RunnableServer(server), "server_thread"); server_thread.start(); System.out.println("[Server] press enter to shutdown> "); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); br.readLine(); System.out.println("[Server] shutting down..."); server.stop(); server_thread.join(); System.out.println("[Server] down, exiting"); }
public void startServer() { try { logger.info("TSimpleServer start ...."); // TMultiplexedProcessor TMultiplexedProcessor processor = new TMultiplexedProcessor(); processor.registerProcessor("Algorithm", new AlgorithmService.Processor<>(new AlgorithmServiceImpl())); TServerSocket serverTransport = new TServerSocket(SERVER_PORT); TServer.Args args = new TServer.Args(serverTransport); args.processor(processor); args.protocolFactory(new TBinaryProtocol.Factory()); // args.protocolFactory(new TJSONProtocol.Factory()); TServer server = new TSimpleServer(args); server.serve(); } catch (Exception e) { logger.error("Server start error!!!"); e.printStackTrace(); } }
ServerThread() throws TTransportException { TMultiplexedProcessor processor = new TMultiplexedProcessor(); for (String beanName : serviceMap.keySet()) { IThriftServerService serverService = (IThriftServerService) serviceMap.getService(beanName); String processorName = serverService.getName(); TProcessor tProcessor = serverService.getProcessor(serverService); processor.registerProcessor(processorName, tProcessor); logger.info("Register a processorName {} processorImpl {}", processorName, tProcessor); } logger.info("init default TServerTransport in addr {} port {}", applicationProperties.getAddr(), applicationProperties.getPort()); TServerTransport tServerTransport = new TServerSocket(new InetSocketAddress(applicationProperties.getAddr(), applicationProperties.getPort())); TThreadPoolServer.Args args = new TThreadPoolServer.Args(tServerTransport); args.processor(processor); args.protocolFactory(tProtocolFactory); server = new TThreadPoolServer(args); }
public void start(CountDownLatch latch, int port) { try { TNonblockingServerSocket serverTransport = new TNonblockingServerSocket(port); //异步IO,需要使用TFramedTransport,它将分块缓存读取。 TTransportFactory transportFactory = new TFramedTransport.Factory(); //使用高密度二进制协议 TProtocolFactory proFactory = new TBinaryProtocol.Factory(); //发布多个服务 TMultiplexedProcessor processor = new TMultiplexedProcessor(); processor.registerProcessor(ClassNameUtils.getClassName(Hello.class), new Hello.Processor<>(new HelloServer())); TServer server = new TThreadedSelectorServer(new TThreadedSelectorServer.Args(serverTransport) .transportFactory(transportFactory) .protocolFactory(proFactory) .processor(processor) ); System.out.println("Starting the hello server..."); latch.countDown(); server.serve(); } catch (Exception e) { e.printStackTrace(); } }
public static void main(String[] args) { try { userProfileServerHandler = new UserProfileServerHandler(); userProfileProcessor = new UserProfileService.Processor(userProfileServerHandler); TMultiplexedProcessor airavataServerProcessor = new TMultiplexedProcessor(); airavataServerProcessor.registerProcessor("UserProfileService", userProfileProcessor); TServerTransport serverTransport = new TServerSocket(9190); TServer server = new TThreadPoolServer(new TThreadPoolServer.Args(serverTransport).processor(airavataServerProcessor)); System.out.println("Starting User Profile server..."); server.serve(); } catch (Exception x) { x.printStackTrace(); } }
/** * Test kaa node initialization service start. * * @throws Exception the exception */ @Test public void testKaaNodeInitializationServiceStart() throws Exception { KaaNodeInitializationService kaaNodeInitializationService = kaaNodeInitializationServiceSpy(); TThreadPoolServer server = Mockito.mock(TThreadPoolServer.class); Mockito.doNothing().when(server).serve(); Mockito.doReturn(server).when(kaaNodeInitializationService).createServer(Mockito.any(TServerTransport.class), Mockito.any(TMultiplexedProcessor.class)); kaaNodeInitializationService.start(); Mockito.verify(controlInitializationService).start(); Mockito.verify(bootstrapInitializationService).start(); Mockito.verify(operationsInitializationService).start(); }
/** * Test kaa node initialization service start with transport exception. * * @throws Exception the exception */ @Test public void testKaaNodeInitializationServiceStartTransportException() throws Exception { KaaNodeInitializationService kaaNodeInitializationService = kaaNodeInitializationServiceSpy(); TThreadPoolServer server = Mockito.mock(TThreadPoolServer.class); Mockito.doThrow(TTransportException.class).when(server).serve(); Mockito.doReturn(server).when(kaaNodeInitializationService).createServer(Mockito.any(TServerTransport.class), Mockito.any(TMultiplexedProcessor.class)); kaaNodeInitializationService.start(); Mockito.verify(controlInitializationService).start(); Mockito.verify(bootstrapInitializationService).start(); Mockito.verify(operationsInitializationService).start(); }
/** * Test kaa node initialization service stop. * * @throws Exception the exception */ @Test public void testKaaNodeInitializationServiceStop() throws Exception { KaaNodeInitializationService kaaNodeInitializationService = kaaNodeInitializationServiceSpy(); TThreadPoolServer server = Mockito.mock(TThreadPoolServer.class); Mockito.doNothing().when(server).serve(); Mockito.doReturn(server).when(kaaNodeInitializationService).createServer(Mockito.any(TServerTransport.class), Mockito.any(TMultiplexedProcessor.class)); kaaNodeInitializationService.start(); kaaNodeInitializationService.stop(); Mockito.verify(controlInitializationService).start(); Mockito.verify(bootstrapInitializationService).start(); Mockito.verify(operationsInitializationService).start(); Mockito.verify(controlInitializationService).stop(); Mockito.verify(bootstrapInitializationService).stop(); Mockito.verify(operationsInitializationService).stop(); }
public void init() { try { TMultiplexedProcessor processor = new TMultiplexedProcessor(); for (ServiceArgs service : serverArgs.getServices()) { String className = service.getService(); if (className.endsWith("$Processor")) { className = className.substring(0, className.indexOf("$Processor")); } processor.registerProcessor(className, service.getProcessor()); } if (serverArgs.getNettyServerArgs() != null) { this.server = new TNettyServer(serverArgs.getNettyServerArgs().ip(serverArgs.getHost()).port(serverArgs.getPort())); } else { TNonblockingServerSocket serverTransport = new TNonblockingServerSocket(new InetSocketAddress(serverArgs.getHost(), serverArgs.getPort())); //异步IO,需要使用TFramedTransport,它将分块缓存读取。 TTransportFactory transportFactory = new TFramedTransport.Factory(); //使用高密度二进制协议 TProtocolFactory proFactory = new TBinaryProtocol.Factory(); // Use this for a multithreaded key this.server = new TThreadedSelectorServer(new TThreadedSelectorServer.Args(serverTransport) .transportFactory(transportFactory) .protocolFactory(proFactory) .processor(processor) ); } log.info("Starting the Thrift key..."); this.server.setServerEventHandler(new TrpcRegistryEventHandler(serverArgs)); this.server.serve(); if (this.serverArgs.getNettyServerArgs() != null) { ((TNettyServer) this.server).waitForClose(); } } catch (Exception e) { log.error("publish thrift key error", e); } }
public void startNettyServer(int port) throws InterruptedException { TMultiplexedProcessor processor = new TMultiplexedProcessor(); processor.registerProcessor(ClassNameUtils.getClassName(Hello.class), new Hello.Processor<>(new HelloServer())); NettyServerArgs serverArgs = new NettyServerArgs() .port(port) .processor(processor); TNettyServer server = new TNettyServer(serverArgs); server.serve(); server.waitForClose(); }
@Override public void init(NettyEmbeddedContext context) { TMultiplexedProcessor tProcessor = new TMultiplexedProcessor(); context.setProcessor(tProcessor); WebApplicationContext webApplicationContext = WebApplicationContextUtils.findWebApplicationContext(context); String[] strarr = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(webApplicationContext, Object.class); for (String s :strarr){ Object target = webApplicationContext.getBean(s); ThriftEndpoint thriftEndpointAnnotation = target.getClass().getAnnotation(ThriftEndpoint.class); if(thriftEndpointAnnotation!=null){ try { Class targetInterface = target.getClass().getInterfaces()[0]; Class processorClass = Class.forName(targetInterface.getName().split("\\$")[0] + "$Processor"); TProcessor p = (TProcessor) processorClass.getDeclaredConstructors()[0].newInstance(target); if(StringUtils.isNotBlank(thriftEndpointAnnotation.serviceName())){ s = thriftEndpointAnnotation.serviceName(); } System.out.println(thriftEndpointAnnotation.serviceName()); logger.info("registerProcessorName : " + s + " registerProcessorClass: " + p.getClass()); tProcessor.registerProcessor(s,p); } catch (Exception e) { logger.error("registerProcessor error : " + e.getMessage() , e); } } } }
private static TProcessor createProcessor() { TMultiplexedProcessor res = new TMultiplexedProcessor(); res.registerProcessor(QueryResultServiceConstants.SERVICE_NAME, new LazyBindingProcessorProvider<>(QueryResultServiceHandler.class, handler -> new QueryResultService.Processor<QueryResultService.Iface>(handler))); res.registerProcessor(KeepAliveServiceConstants.SERVICE_NAME, new LazyBindingProcessorProvider<>( KeepAliveServiceHandler.class, handler -> new KeepAliveService.Processor<KeepAliveService.Iface>(handler))); res.registerProcessor(IdentityCallbackServiceConstants.SERVICE_NAME, new LazyBindingProcessorProvider<>(IdentityCallbackHandler.class, handler -> new IdentityCallbackService.Processor<IdentityCallbackService.Iface>(handler))); // when adding new processors, update NUMBER_OF_PROCESSORS return res; }
/** * Creates the server. * * @param serverTransport the server transport * @param processor the processor * @return the t server */ public TServer createServer(TServerTransport serverTransport, TMultiplexedProcessor processor) { TThreadPoolServer.Args args = new Args(serverTransport).processor(processor); args.stopTimeoutVal = 3; args.stopTimeoutUnit = TimeUnit.SECONDS; SynchronousQueue<Runnable> executorQueue = // NOSONAR new SynchronousQueue<Runnable>(); executorService = new ThreadPoolExecutor(args.minWorkerThreads, args.maxWorkerThreads, 60, TimeUnit.SECONDS, executorQueue); args.executorService = executorService; return new TThreadPoolServer(args); }
@Override public void run() { LOG.info("Initializing Thrift Service for Bootstrap Server...."); LOG.info("thrift host: {}", thriftHost); LOG.info("thrift port: {}", thriftPort); try { TMultiplexedProcessor processor = new TMultiplexedProcessor(); BootstrapThriftService.Processor<BootstrapThriftService.Iface> bootstrapProcessor = new BootstrapThriftService.Processor<BootstrapThriftService.Iface>( bootstrapThriftService); processor.registerProcessor(KaaThriftService.BOOTSTRAP_SERVICE.getServiceName(), bootstrapProcessor); TServerTransport serverTransport = new TServerSocket(new InetSocketAddress(thriftHost, thriftPort)); server = new TThreadPoolServer(new Args(serverTransport).processor(processor)); LOG.info("Bootstrap test Server {}:{} Started.", thriftHost, thriftPort); synchronized (startSync) { startComplete = true; startSync.notify(); } server.serve(); LOG.info("Bootstrap test Server {}:{} Stopped.", thriftHost, thriftPort); } catch (TTransportException e) { LOG.error("TTransportException", e); } finally { synchronized (stopSync) { stopComplete = true; bootstrapThriftService.reset(); stopSync.notify(); } } }
@Override public boolean register(TMultiplexedProcessor multiplexedProcessor) throws Exception { SentryHDFSServiceProcessor sentryServiceHandler = new SentryHDFSServiceProcessor(); LOGGER.info("Calling registerProcessor from SentryHDFSServiceProcessorFactory"); TProcessor processor = new ProcessorWrapper(sentryServiceHandler); multiplexedProcessor.registerProcessor( SentryHDFSServiceClient.SENTRY_HDFS_SERVICE_NAME, processor); return true; }
@Override public boolean register(TMultiplexedProcessor multiplexedProcessor) throws Exception { SentryGenericPolicyProcessor processHandler = new SentryGenericPolicyProcessor(conf); TProcessor processor = new SentryGenericPolicyProcessorWrapper<SentryGenericPolicyService.Iface>( processHandler); multiplexedProcessor.registerProcessor(SentryGenericPolicyProcessor.SENTRY_GENERIC_SERVICE_NAME, processor); return true; }
public boolean register(TMultiplexedProcessor multiplexedProcessor) throws Exception { SentryPolicyStoreProcessor sentryServiceHandler = new SentryPolicyStoreProcessor(SentryPolicyStoreProcessor.SENTRY_POLICY_SERVICE_NAME, conf); TProcessor processor = new SentryProcessorWrapper<SentryPolicyService.Iface>(sentryServiceHandler); multiplexedProcessor.registerProcessor(SentryPolicyStoreProcessor.SENTRY_POLICY_SERVICE_NAME, processor); return true; }
public void setProcessor(TMultiplexedProcessor processor) { this.processor = processor; }
public TMultiplexedProcessor getProcessor() { return this.processor; }
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; }
public static void main(String[] args) throws Exception { EventLoopGroup workerGroup = new NioEventLoopGroup(); EventLoopGroup bossGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup); b.channel(NioServerSocketChannel.class); b.handler(new LoggingHandler(LogLevel.DEBUG)); b.childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { TMultiplexedProcessor multiprocessor = new TMultiplexedProcessor(); multiprocessor.registerProcessor("Calculator", new Calculator.Processor(new CalculatorHandler())); multiprocessor.registerProcessor("Scribe", new scribe.Processor<scribe.Iface>(new scribe.Iface() { @Override public ResultCode Log(List<LogEntry> messages) throws TException { for (LogEntry message : messages) { log.info("{}: {}", message.getCategory(), message.getMessage()); } return ResultCode.OK; } })); ThriftServerDef def = new ThriftServerDefBuilder().withProcessor(multiprocessor).build(); ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast("frameDecoder", new ThriftFrameDecoder(def.getMaxFrameSize(), def.getInProtocolFactory())); pipeline.addLast("dispatcher", new NiftyDispatcher(def)); } }); b.option(ChannelOption.SO_BACKLOG, 128); b.childOption(ChannelOption.SO_KEEPALIVE, true); log.debug("configuration serverBootstrap"); if (log.isInfoEnabled()) { log.info("Start server with port: {} ", 9090); } else if (log.isWarnEnabled()) { log.warn("Start server with port: {} ", 9090); } else if (log.isErrorEnabled()) { log.error("Start server with port: {} ", 9090); } Channel serverChannel = b.bind(9090).sync().channel().closeFuture().sync().channel(); } finally { workerGroup.shutdownGracefully(); bossGroup.shutdownGracefully(); } }
/** * Start thrift. */ private void startThrift(final CountDownLatch thriftStartupLatch, final CountDownLatch thriftShutdownLatch) { Runnable thriftRunnable = new Runnable() { @Override public void run() { LOG.info("Initializing Thrift Service for Kaa Node Server...."); LOG.info("host: " + getNodeConfig().getThriftHost()); LOG.info("port: " + getNodeConfig().getThriftPort()); try { TMultiplexedProcessor processor = new TMultiplexedProcessor(); KaaNodeThriftService.Processor<KaaNodeThriftService.Iface> kaaNodeProcessor = new KaaNodeThriftService.Processor<>(kaaNodeThriftService); processor.registerProcessor(KAA_NODE_SERVICE.getServiceName(), kaaNodeProcessor); if (getNodeConfig().isBootstrapServiceEnabled()) { BootstrapThriftService.Processor<BootstrapThriftService.Iface> bootstrapProcessor = new BootstrapThriftService.Processor<>(bootstrapThriftService); processor.registerProcessor(BOOTSTRAP_SERVICE.getServiceName(), bootstrapProcessor); } if (getNodeConfig().isOperationsServiceEnabled()) { OperationsThriftService.Processor<OperationsThriftService.Iface> operationsProcessor = new OperationsThriftService.Processor<>(operationsThriftService); processor.registerProcessor(OPERATIONS_SERVICE.getServiceName(), operationsProcessor); } TServerTransport serverTransport = createServerSocket(); server = createServer(serverTransport, processor); LOG.info("Thrift Kaa Node Server Started."); thriftStartupLatch.countDown(); server.serve(); if (executorService != null && !executorService.isTerminated()) { for (TSocketWrapper socket : new ArrayList<>(openedSockets)) { if (socket.getSocket() != null && !socket.getSocket().isClosed()) { socket.close(); } } LOG.info("Terminating executor service."); executorService.shutdownNow(); } LOG.info("Thrift Kaa Node Server Stopped."); thriftShutdownLatch.countDown(); } catch (TTransportException ex) { LOG.error("TTransportException", ex); } finally { if (thriftStartupLatch.getCount() > 0) { thriftStartupLatch.countDown(); } if (thriftShutdownLatch.getCount() > 0) { LOG.info("Thrift Kaa Node Server Stopped."); thriftShutdownLatch.countDown(); } } } }; new Thread(thriftRunnable).start(); }
/** * Before test. * * @throws Exception the exception */ @Before public void beforeTest() throws Exception { if (!thriftServerStarted) { CliThriftService.Processor<CliThriftService.Iface> cliProcessor = new CliThriftService.Processor<CliThriftService.Iface>( new TestCliThriftService(THRIFT_SERVER_SHORT_NAME)); TMultiplexedProcessor processor = new TMultiplexedProcessor(); processor.registerProcessor(KaaThriftService.KAA_NODE_SERVICE.getServiceName(), cliProcessor); TServerTransport serverTransport = new TServerSocket( new InetSocketAddress(HOST, PORT)); server = new TThreadPoolServer( new Args(serverTransport).processor(processor)); thriftServerThread = new Thread(new Runnable() { @Override public void run() { LOG.info("Thrift Server started."); server.serve(); LOG.info("Thrift Server stopped."); } }); thriftServerThread.start(); Thread.sleep(100); thriftServerStarted = true; } cliSession = new CliSessionState(); cliSession.in = System.in; systemOut = new ByteArrayOutputStream(); PrintStream out = new PrintStream(systemOut, true, "UTF-8"); System.setOut(out); systemErr = new ByteArrayOutputStream(); PrintStream err = new PrintStream(systemErr, true, "UTF-8"); System.setErr(err); cliSession.out = System.out; cliSession.err = System.err; CliSessionState.start(cliSession); }
public AbstractRunnableServiceWrapper(ApplicationContext applicationContext, String serviceName) { LOGGER.debug("Service setup: {}", serviceName); this.multiplexedProcessor = new TMultiplexedProcessor(); this.applicationContext = applicationContext; this.serviceName = serviceName; }
@Override public void run() { LOG.info("Initializing Thrift Service for Operations Server...."); LOG.info("thrift host: {}", thriftHost); LOG.info("thrift port: {}", thriftPort); registerZK(); try { TMultiplexedProcessor processor = new TMultiplexedProcessor(); OperationsThriftService.Processor<OperationsThriftService.Iface> operationsProcessor = new OperationsThriftService.Processor<OperationsThriftService.Iface>( operationsThriftService); processor.registerProcessor(KaaThriftService.OPERATIONS_SERVICE.getServiceName(), operationsProcessor); TServerTransport serverTransport = new TServerSocket(new InetSocketAddress(thriftHost, thriftPort)); server = new TThreadPoolServer(new Args(serverTransport).processor(processor)); LOG.info("Operations Server {}:{} Started.", thriftHost, thriftPort); server.serve(); LOG.info("Operations Server {}:{} Stopped.", thriftHost, thriftPort); } catch (TTransportException e) { LOG.error("TTransportException", e); } }
public abstract boolean register(TMultiplexedProcessor processor) throws Exception;