org.apache.thrift.transport.TServerSocket Java Examples

The following examples show how to use org.apache.thrift.transport.TServerSocket. 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: TestThriftClientPool.java    From thrift-client-pool-java with Artistic License 2.0 6 votes vote down vote up
@BeforeClass
public static void setUp() {
    int port = 9090;

    try {
        TServerTransport serverTransport = new TServerSocket(port);

        Args processor = new TThreadPoolServer.Args(serverTransport)
                .inputTransportFactory(new TFramedTransport.Factory())
                .outputTransportFactory(new TFramedTransport.Factory())
                .processor(new Processor<>(new TestThriftServiceHandler()));
        //            processor.maxWorkerThreads = 20;
        TThreadPoolServer server = new TThreadPoolServer(processor);

        logger.info("Starting test server...");
        new Thread(server::serve).start();
        Thread.sleep(1000); // waiting server init
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example #2
Source File: DKSearchService.java    From dk-fitting with Apache License 2.0 6 votes vote down vote up
/**
 *
 * 简单的单线程模式
 *
 */
public  void  startService(){
    System.out.println( " start ...." );
    //单接口声明
    //TProcessor tProcessor=new DKSearchOutput.Processor<DKSearchOutput.Iface>( new DKSearchOutputImpl() );
    //多接口声明
    TMultiplexedProcessor processor = new TMultiplexedProcessor();
    processor.registerProcessor( "DKSearchOutput",new DKSearchOutput.Processor<DKSearchOutput.Iface>( new DKSearchOutputImpl() ) );
    processor.registerProcessor( "DKSearchInput",new DKSearchInput.Processor<DKSearchInput.Iface>(new DKSearchInputImpl()  ) );
    processor.registerProcessor( "DKSearchService",new SearchService.Processor<SearchService.Iface>(new SearchServiceImpl() ) );
    try {
        TServerSocket serverSocket=new TServerSocket( Integer.valueOf(prop.get("dkSearch.port")) );
        TServer.Args targs=new TServer.Args( serverSocket );
        targs.processor( processor );
        //二进制TBinaryProtocol
        //二进制高密度TCompactProtocol
        targs.protocolFactory( new TCompactProtocol.Factory(  ) );
        TServer tServer=new TSimpleServer( targs );
        tServer.serve();
    } catch (TTransportException e) {
        System.err.println("Service Start error");
        e.printStackTrace();
    }
}
 
Example #3
Source File: DKSearchService.java    From dk-fitting with Apache License 2.0 6 votes vote down vote up
/**
 *  线程池服务模型,使用标准的阻塞式IO,预先创建一组线程处理请求。
 */
public void startTThreadPoolServer() {
    try {
        System.out.println("UserInfoServiceDemo TThreadPoolServer start ....");
        TMultiplexedProcessor processor = new TMultiplexedProcessor();
        processor.registerProcessor( "DKSearchOutput",new DKSearchOutput.Processor<DKSearchOutput.Iface>( new DKSearchOutputImpl() ) );
        processor.registerProcessor( "DKSearchInput",new DKSearchInput.Processor<DKSearchInput.Iface>(new DKSearchInputImpl()  ) );
        processor.registerProcessor( "DKSearchService",new SearchService.Processor<SearchService.Iface>(new SearchServiceImpl() ) );
        //TProcessor tprocessor = new UserInfoService.Processor<UserInfoService.Iface>(new UserInfoServiceImpl());
        TServerSocket serverTransport = new TServerSocket( Integer.valueOf(prop.get("dkSearch.port")));
        TThreadPoolServer.Args ttpsArgs = new TThreadPoolServer.Args(serverTransport);
        ttpsArgs.processor(processor);
        ttpsArgs.protocolFactory(new TBinaryProtocol.Factory());
        // 线程池服务模型,使用标准的阻塞式IO,预先创建一组线程处理请求。
        TServer server = new TThreadPoolServer(ttpsArgs);
        server.serve();
    } catch (Exception e) {
        System.out.println("Server start error!!!");
        e.printStackTrace();

    }

}
 
Example #4
Source File: DKMLServer.java    From dk-fitting with Apache License 2.0 6 votes vote down vote up
/**
 * 阻塞式、多线程处理
 *
 * @param args
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public static void main(String[] args) {
    try {
        int port = Integer.valueOf(prop.get("dkml.port"));
        //设置传输通道,普通通道
        TServerTransport serverTransport = new TServerSocket(port);
        //使用高密度二进制协议
        TProtocolFactory proFactory = new TCompactProtocol.Factory();
        //设置处理器
        TProcessor processor = new DKML.Processor(new DKMLImpl());
        //创建服务器
        TServer server = new TThreadPoolServer(
                new TThreadPoolServer.Args(serverTransport)
                        .protocolFactory(proFactory)
                        .processor(processor)
        );

        System.out.println("Start server on port "+ port +"...");
        server.serve();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example #5
Source File: CoronaTaskTracker.java    From RDFS with Apache License 2.0 6 votes vote down vote up
private synchronized void initializeClusterManagerCallbackServer()
    throws IOException {
  // Create thrift RPC to serve ClusterManager
  int soTimeout = fConf.getInt(
      CORONA_TASK_TRACKER_SERVER_CLIENTTIMEOUT_KEY, 30 * 1000);
  ServerSocket serverSocket = new ServerSocket();
  serverSocket.setReuseAddress(true);
  serverSocket.bind(new InetSocketAddress(0));
  TServerSocket tSocket = new TServerSocket(serverSocket, soTimeout);
  CoronaTaskTrackerService.Processor proc =
      new CoronaTaskTrackerService.Processor(this);
  TBinaryProtocol.Factory protocolFactory =
      new TBinaryProtocol.Factory(true, true);
  TThreadPoolServer.Args args = new TThreadPoolServer.Args(tSocket);
  args.processor(proc);
  args.protocolFactory(protocolFactory);
  clusterManagerCallbackServer = new TThreadPoolServer(args);
  clusterManagerCallbackServerThread =
      new TServerThread(clusterManagerCallbackServer);
  clusterManagerCallbackServerThread.start();
  clusterManagerCallbackServerAddr = new InetAddress(
      getLocalHostname(), serverSocket.getLocalPort());
  LOG.info("SessionServer up at " + serverSocket.getLocalSocketAddress());
}
 
Example #6
Source File: ServerTrans.java    From ThriftBook with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) 
       throws TTransportException, UnsupportedEncodingException {
    final String msg = "Hello Thrift!\n";
    final String stop_cmd = "STOP";
    final int buf_size = 1024*8;
    byte[] buf = new byte[buf_size];
    final int port = 9090;

    TServerTransport acceptor = new TServerSocket(9090);
    acceptor.listen();
    System.out.println("[Server] listening on port: " + port);
    
    String input;
    do {
        TTransport trans = acceptor.accept();
        int len = trans.read(buf, 0, buf_size);
        input = new String(buf, 0, len,"UTF-8");
        System.out.println("[Server] handling request: " + input);
        trans.write(msg.getBytes());
        trans.flush();
        trans.close();
    } while (! stop_cmd.regionMatches(0, input, 0, 4)); 

    System.out.println("[Server] exiting");
    acceptor.close();
}
 
Example #7
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 #8
Source File: ThriftITest.java    From java-specialagent with Apache License 2.0 6 votes vote down vote up
public static void main(final String[] args) throws Exception {
  final CountDownLatch latch = TestUtil.initExpectedSpanLatch(2);
  final TServerTransport serverTransport = new TServerSocket(port);
  final TServer server = startNewThreadPoolServer(serverTransport);

  final TTransport transport = new TSocket("localhost", port);
  transport.open();

  final TProtocol protocol = new TBinaryProtocol(transport);

  final CustomService.Client client = new CustomService.Client(protocol);
  final String res = client.say("one", "two");
  if (!"Say one two".equals(res))
    throw new AssertionError("ERROR: wrong result");

  TestUtil.checkSpan(latch, new ComponentSpanCount("java-thrift", 2, true));

  server.stop();
  transport.close();
}
 
Example #9
Source File: ThriftServer.java    From hbase with Apache License 2.0 6 votes vote down vote up
protected TServer getTThreadPoolServer(TProtocolFactory protocolFactory, TProcessor processor,
    TTransportFactory transportFactory, InetSocketAddress inetSocketAddress) throws Exception {
  LOG.info("starting HBase ThreadPool Thrift server on " + inetSocketAddress.toString());
  // Thrift's implementation uses '0' as a placeholder for 'use the default.'
  int backlog = conf.getInt(BACKLOG_CONF_KEY, BACKLOG_CONF_DEAFULT);
  int readTimeout = conf.getInt(THRIFT_SERVER_SOCKET_READ_TIMEOUT_KEY,
      THRIFT_SERVER_SOCKET_READ_TIMEOUT_DEFAULT);
  TServerTransport serverTransport = new TServerSocket(
      new TServerSocket.ServerSocketTransportArgs().
          bindAddr(inetSocketAddress).backlog(backlog).
          clientTimeout(readTimeout));

  TBoundedThreadPoolServer.Args serverArgs =
      new TBoundedThreadPoolServer.Args(serverTransport, conf);
  serverArgs.processor(processor).transportFactory(transportFactory)
      .protocolFactory(protocolFactory);
  return new TBoundedThreadPoolServer(serverArgs, metrics);
}
 
Example #10
Source File: TestHiveMetastore.java    From iceberg with Apache License 2.0 6 votes vote down vote up
public void start() {
  try {
    hiveLocalDir = createTempDirectory("hive", asFileAttribute(fromString("rwxrwxrwx"))).toFile();
    File derbyLogFile = new File(hiveLocalDir, "derby.log");
    System.setProperty("derby.stream.error.file", derbyLogFile.getAbsolutePath());
    setupMetastoreDB("jdbc:derby:" + getDerbyPath() + ";create=true");

    TServerSocket socket = new TServerSocket(0);
    int port = socket.getServerSocket().getLocalPort();
    hiveConf = newHiveConf(port);
    server = newThriftServer(socket, hiveConf);
    executorService = Executors.newSingleThreadExecutor();
    executorService.submit(() -> server.serve());
  } catch (Exception e) {
    throw new RuntimeException("Cannot start TestHiveMetastore", e);
  }
}
 
Example #11
Source File: ThriftServerApplication.java    From spring-boot-demo with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
    SpringApplication.run(ThriftServerApplication.class, args);

    try {
        System.out.println("服务端开启....");
        TProcessor tprocessor = new Hello.Processor<Hello.Iface>(new HelloServiceImpl());
        // 简单的单线程服务模型
        TServerSocket serverTransport = new TServerSocket(9898);
        TServer.Args tArgs = new TServer.Args(serverTransport);
        tArgs.processor(tprocessor);
        tArgs.protocolFactory(new TBinaryProtocol.Factory());
        TServer server = new TSimpleServer(tArgs);
        server.serve();
    } catch (TTransportException e) {
        e.printStackTrace();
    }
}
 
Example #12
Source File: TCPThriftAuthenticationService.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
public void start() throws TTransportException, UnknownHostException {
    InetAddress inetAddress = InetAddress.getByName(hostName);

    TSSLTransportFactory.TSSLTransportParameters params =
            new TSSLTransportFactory.TSSLTransportParameters();
    params.setKeyStore(keyStore, keyStorePassword);

    TServerSocket serverTransport;

    serverTransport = TSSLTransportFactory.getServerSocket(port, clientTimeout, inetAddress, params);


    AuthenticatorService.Processor<AuthenticatorServiceImpl> processor =
            new AuthenticatorService.Processor<AuthenticatorServiceImpl>(
                    new AuthenticatorServiceImpl(thriftAuthenticatorService));
    authenticationServer = new TThreadPoolServer(
            new TThreadPoolServer.Args(serverTransport).processor(processor));
    Thread thread = new Thread(new ServerRunnable(authenticationServer));
    if (log.isDebugEnabled()) {
        log.debug("Thrift Authentication Service started at ssl://" + hostName + ":" + port);
    }
    thread.start();
}
 
Example #13
Source File: HiveTableBaseTest.java    From iceberg with Apache License 2.0 6 votes vote down vote up
private TServer thriftServer() throws IOException,
        TTransportException,
        MetaException,
        InvocationTargetException,
        NoSuchMethodException,
        IllegalAccessException,
        NoSuchFieldException {
  final TServerSocketKeepAlive socket = new TServerSocketKeepAlive(new TServerSocket(0));
  this.hiveConf = hiveConf(new Configuration(), socket.getServerSocket().getLocalPort());
  HiveMetaStore.HMSHandler baseHandler = new HiveMetaStore.HMSHandler("new db based metaserver", hiveConf);
  IHMSHandler handler = RetryingHMSHandler.getProxy(hiveConf, baseHandler, true);
  final TTransportFactory transportFactory = new TTransportFactory();
  final TSetIpAddressProcessor<IHMSHandler> processor = new TSetIpAddressProcessor<>(handler);

  TThreadPoolServer.Args args = new TThreadPoolServer.Args(socket)
          .processor(processor)
          .transportFactory(transportFactory)
          .protocolFactory(new TBinaryProtocol.Factory())
          .minWorkerThreads(3)
          .maxWorkerThreads(5);

  return new TThreadPoolServer(args);
}
 
Example #14
Source File: HelloServerConfig.java    From jigsaw-payment with Apache License 2.0 6 votes vote down vote up
@Bean(name = "pool-server")
public TServer poolServer() throws Exception {
	TServerTransport transport = new TServerSocket(this.port());

	TThreadPoolServer.Args args = new TThreadPoolServer.Args(transport);
	args.transportFactory(new TTransportFactory());
	args.protocolFactory(new TBinaryProtocol.Factory());

	args.processor(this.processor());
	args.executorService(new ThreadPoolExecutor(env.getProperty(
			"rpc.server.min.worker.threads", Integer.class, 512), env
			.getProperty("rpc.server.max.worker.threads", Integer.class,
					65535), env.getProperty(
			"rpc.server.thread.keep.alive.time", Long.class, 600l),
			TimeUnit.SECONDS, new SynchronousQueue<Runnable>()));

	return new TThreadPoolServer(args);
}
 
Example #15
Source File: TestThriftServiceStarter.java    From thrift-client-pool-java with Artistic License 2.0 6 votes vote down vote up
public static void main(String[] args) {
    int port = 9090;

    try {
        TServerTransport serverTransport = new TServerSocket(port);

        Args processor = new TThreadPoolServer.Args(serverTransport)
                .inputTransportFactory(new TFramedTransport.Factory())
                .outputTransportFactory(new TFramedTransport.Factory())
                .processor(new Processor<>(new TestThriftServiceHandler()));
        //            processor.maxWorkerThreads = 20;
        TThreadPoolServer server = new TThreadPoolServer(processor);

        System.out.println("Starting the server...");
        server.serve();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example #16
Source File: SyncEchoTestServer.java    From pinpoint with Apache License 2.0 6 votes vote down vote up
public static SyncEchoTestServer<TSimpleServer> simpleServer(final TestEnvironment environment)
        throws TTransportException {
    TSimpleServer server = new TSimpleServer(new TSimpleServer.Args(new TServerSocket(environment.getPort()))
            .processor(getProcessor()).inputProtocolFactory(environment.getProtocolFactory())
            .outputProtocolFactory(environment.getProtocolFactory()));
    return new SyncEchoTestServer<TSimpleServer>(server, environment) {
        @Override
        public SyncEchoTestClient getSynchronousClient() throws TTransportException {
            return new SyncEchoTestClient.Client(environment);
        }

        @Override
        public AsyncEchoTestClient getAsynchronousClient() throws IOException {
            return new AsyncEchoTestClient.Client(environment);
        }
    };
}
 
Example #17
Source File: AbstractThriftServer.java    From metacat with Apache License 2.0 6 votes vote down vote up
/**
 * Server initialization.
 *
 * @throws Exception error
 */
public void start() throws Exception {
    log.info("initializing thrift server {}", getServerName());
    final ThreadFactory threadFactory = new ThreadFactoryBuilder()
        .setNameFormat(threadPoolNameFormat)
        .setUncaughtExceptionHandler((t, e) -> log.error("Uncaught exception in thread: {}", t.getName(), e))
        .build();
    final ExecutorService executorService = new ThreadPoolExecutor(
        Math.min(2, config.getThriftServerMaxWorkerThreads()),
        config.getThriftServerMaxWorkerThreads(),
        60L,
        TimeUnit.SECONDS,
        new SynchronousQueue<>(),
        threadFactory
    );
    RegistryUtil.registerThreadPool(registry, threadPoolNameFormat, (ThreadPoolExecutor) executorService);
    final int timeout = config.getThriftServerSocketClientTimeoutInSeconds() * 1000;
    final TServerTransport serverTransport = new TServerSocket(portNumber, timeout);
    startServing(executorService, serverTransport);
}
 
Example #18
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 #19
Source File: MetaStoreProxyServer.java    From waggle-dance with Apache License 2.0 6 votes vote down vote up
private TServerSocket createServerSocket(boolean useSSL, int port) throws IOException, TTransportException {
  TServerSocket serverSocket = null;
  // enable SSL support for HMS
  List<String> sslVersionBlacklist = new ArrayList<>(Arrays.asList(hiveConf.getVar(ConfVars.HIVE_SSL_PROTOCOL_BLACKLIST).split(",")));
  if (!useSSL) {
    serverSocket = HiveAuthUtils.getServerSocket(null, port);
  } else {
    String keyStorePath = hiveConf.getVar(ConfVars.HIVE_METASTORE_SSL_KEYSTORE_PATH).trim();
    if (keyStorePath.isEmpty()) {
      throw new IllegalArgumentException(
          ConfVars.HIVE_METASTORE_SSL_KEYSTORE_PASSWORD.varname + " Not configured for SSL connection");
    }
    String keyStorePassword = ShimLoader
        .getHadoopShims()
        .getPassword(hiveConf, HiveConf.ConfVars.HIVE_METASTORE_SSL_KEYSTORE_PASSWORD.varname);
    serverSocket = HiveAuthUtils.getServerSSLSocket(null, port, keyStorePath, keyStorePassword, sslVersionBlacklist);
  }
  return serverSocket;
}
 
Example #20
Source File: SyncEchoTestServer.java    From pinpoint with Apache License 2.0 6 votes vote down vote up
public static SyncEchoTestServer<TThreadPoolServer> threadedPoolServer(final TestEnvironment environment)
        throws TTransportException {
    TThreadPoolServer server = new TThreadPoolServer(new TThreadPoolServer.Args(new TServerSocket(
            environment.getPort())).processor(getProcessor())
            .inputProtocolFactory(environment.getProtocolFactory())
            .outputProtocolFactory(environment.getProtocolFactory()));
    return new SyncEchoTestServer<TThreadPoolServer>(server, environment) {
        @Override
        public SyncEchoTestClient getSynchronousClient() throws TTransportException {
            return new SyncEchoTestClient.Client(environment);
        }

        @Override
        public AsyncEchoTestClient getAsynchronousClient() throws IOException {
            return new AsyncEchoTestClient.Client(environment);
        }
    };
}
 
Example #21
Source File: ThriftLegacySource.java    From mt-flume with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("deprecation")
@Override
public void start() {
  try {
    InetSocketAddress bindAddr = new InetSocketAddress(host, port);
    serverTransport = new TServerSocket(bindAddr);
    ThriftFlumeEventServer.Processor processor =
        new ThriftFlumeEventServer.Processor(new ThriftFlumeEventServerImpl());
    server = new TThreadPoolServer(new TThreadPoolServer.
        Args(serverTransport).processor(processor));
  } catch (TTransportException e) {
    throw new FlumeException("Failed starting source", e);
  }
  ThriftHandler thriftHandler = new ThriftHandler(server);
  thriftHandlerThread = new Thread(thriftHandler);
  thriftHandlerThread.start();
  super.start();
}
 
Example #22
Source File: SessionDriver.java    From RDFS with Apache License 2.0 6 votes vote down vote up
/**
 * Start the SessionDriver callback server
 * @param conf the corona configuration for this session
 * @return the server socket of the callback server
 * @throws IOException
 */
private ServerSocket initializeServer(CoronaConf conf) throws IOException {
  // Choose any free port.
  ServerSocket sessionServerSocket =
    new ServerSocket(0, 0, getLocalAddress());
  TServerSocket tServerSocket = new TServerSocket(sessionServerSocket,
                                                  conf.getCMSoTimeout());

  TFactoryBasedThreadPoolServer.Args args =
    new TFactoryBasedThreadPoolServer.Args(tServerSocket);
  args.processor(new SessionDriverServiceProcessor(incoming));
  args.transportFactory(new TTransportFactory());
  args.protocolFactory(new TBinaryProtocol.Factory(true, true));
  args.stopTimeoutVal = 0;
  server = new TFactoryBasedThreadPoolServer(
    args, new TFactoryBasedThreadPoolServer.DaemonThreadFactory());
  return sessionServerSocket;
}
 
Example #23
Source File: TestClientsWithApacheServer.java    From drift with Apache License 2.0 6 votes vote down vote up
private static TServerSocket createServerTransport(boolean secure)
        throws TTransportException
{
    if (!secure) {
        return new TServerSocket(0);
    }

    try {
        SSLContext serverSslContext = ClientTestUtils.getServerSslContext();
        SSLServerSocket serverSocket = (SSLServerSocket) serverSslContext.getServerSocketFactory().createServerSocket(0);
        return new TServerSocket(serverSocket);
    }
    catch (Exception e) {
        throw new TTransportException("Error initializing secure socket", e);
    }
}
 
Example #24
Source File: ServiceProvider.java    From ourea with Apache License 2.0 5 votes vote down vote up
/**
 * 启动thrift server,如果存在server容器或者多个service,则一些需要设置为daemon模式
 */
private void startServer() throws Exception {

    TServerSocket serverTransport = new TServerSocket(serverConfig.getPort());
    TThreadPoolServer.Args args = new TThreadPoolServer.Args(serverTransport);
    args.maxWorkerThreads = serverConfig.getMaxWorkerThreads();
    args.minWorkerThreads = serverConfig.getMinWorkerThreads();
    args.protocolFactory(new TBinaryProtocol.Factory());

    TProcessor tProcessor = getProcessorIface(getIfaceClass());
    args.processor(tProcessor);
    final TServer server = new TThreadPoolServer(args);
    server.setServerEventHandler(serverConfig.getServerEventHandler());
    Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            server.serve();
        }
    });
    thread.setDaemon(serverConfig.isDaemonRun());
    thread.start();
    Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
        @Override public void run() {
            if (!serverConfig.isDirectInvoke()) {
                unZkRegister(providerInfo, serviceInfo);
            }
            server.stop();
        }
    }));

    LOGGER.info("----------------start thrift server--------------");
}
 
Example #25
Source File: ServerFrame.java    From ThriftBook with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) 
         throws TTransportException, UnsupportedEncodingException, SocketException {
     final String msg = "Hello Thrift!\n";
     final String stop_cmd = "STOP";
     final int buf_size = 1024*8;
     byte[] buf = new byte[buf_size];
     final int port = 9090;

     TServerTransport acceptor = new TServerSocket(port);
     acceptor.listen();
     System.out.println("[Server] listening on port " + port);

     while (true) {
         TTransport trans_ep = acceptor.accept();
TTransport trans = new TFramedTransport(trans_ep);
         int len = trans.read(buf, 0, buf_size);
         String input = new String(buf, 0, len, "UTF-8");
         System.out.println("[Server] handling request: " + input);
         trans.write(msg.getBytes());
         trans.flush();
         trans.close();
         if (stop_cmd.regionMatches(0, input, 0, 4)) {
            break;
         }
     }
     System.out.println("[Server] exiting");
     acceptor.close();
 }
 
Example #26
Source File: HelloServer.java    From ThriftBook with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws TTransportException {
    TServerSocket trans_svr = new TServerSocket(9090);
    TProcessor proc = new helloSvc.Processor<>(new MessageHandler());
    TServer server =
            new TSimpleServer(
                    new TSimpleServer.Args(trans_svr)
                            .processor(proc)
            );
    System.out.println("[Server] waiting for connections");
    server.serve();
}
 
Example #27
Source File: HelloServer.java    From ThriftBook with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws TTransportException {
    TServerSocket trans_svr = new TServerSocket(9090);
    TProcessor proc = new helloSvc.Processor<>(new MessageHandler());
    TSimpleServer server = 
        new TSimpleServer(
            new TSimpleServer.Args(trans_svr)
                .processor(proc)
        );
    System.out.println("[Server] waiting for connections");
    server.serve();
}
 
Example #28
Source File: AbstractTest.java    From dubbox with Apache License 2.0 5 votes vote down vote up
protected void init() throws Exception {
    TServerTransport serverTransport = new TServerSocket( PORT );

    TBinaryProtocol.Factory bFactory = new TBinaryProtocol.Factory();

    server = new TThreadPoolServer(
            new TThreadPoolServer.Args( serverTransport )
                    .inputProtocolFactory( bFactory )
                    .outputProtocolFactory( bFactory )
                    .inputTransportFactory( getTransportFactory() )
                    .outputTransportFactory( getTransportFactory() )
                    .processor( getProcessor() ) );

    Thread startTread = new Thread() {

        @Override
        public void run() {
            server.serve();
        }

    };

    startTread.setName( "thrift-server" );

    startTread.start();

    while( !server.isServing() ) {
        Thread.sleep( 100 );
    }

    protocol = ExtensionLoader.getExtensionLoader(Protocol.class)
            .getExtension( ThriftProtocol.NAME );

    invoker = protocol.refer( getInterface(), getUrl() );

}
 
Example #29
Source File: FactoryServer.java    From ThriftBook with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws TTransportException {
  TServerSocket trans_svr = new TServerSocket(9090);
  TProcessor proc = new Message.Processor<>(new MessageHandler());
  
  TServer server = new TThreadPoolServer(
          new TThreadPoolServer.Args(trans_svr)
            .processor(proc)
            .protocolFactory(new TJSONProtocol.Factory())
            .inputTransportFactory(new TFramedTransport.Factory())
            .outputTransportFactory(new TWritelogTransportFactory(100)));
  server.serve();
}
 
Example #30
Source File: ThriftServer.java    From ThriftBook with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args)
        throws TTransportException, IOException {
    TradeHistory.Processor proc = 
        new TradeHistory.Processor(new TradeHistoryHandler());
    TServerSocket trans_svr = 
        new TServerSocket(9090);
    TThreadPoolServer server = 
        new TThreadPoolServer(new TThreadPoolServer.Args(trans_svr)
                .protocolFactory(new TJSONProtocol.Factory())
                .processor(proc));
    System.out.println("[Server] listening of port 9090");
    server.serve();
}