Nifty - thrift服务端和客户端实现


Apache
跨平台
Java

软件简介

Nifty是facebook公司开源的,基于nettythrift服务端和客户端实现。

然后使用此包就可以快速发布出基于netty的高效的服务端和客户端代码。

示例:

public void startServer() {
    // Create the handler
    MyService.Iface serviceInterface = new MyServiceHandler();

    // Create the processor
    TProcessor processor = new MyService.Processor<>(serviceInterface);

    // Build the server definition
    ThriftServerDef serverDef = new ThriftServerDefBuilder().withProcessor(processor)
                                                            .build();

    // Create the server transport
    final NettyServerTransport server = new NettyServerTransport(serverDef,
                                                                 new NettyConfigBuilder(),
                                                                 new DefaultChannelGroup(),
                                                                 new HashedWheelTimer());

    // Create netty boss and executor thread pools
    ExecutorService bossExecutor = Executors.newCachedThreadPool();
    ExecutorService workerExecutor = Executors.newCachedThreadPool();

    // Start the server
    server.start(bossExecutor, workerExecutor);

    // Arrange to stop the server at shutdown
    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            try {
                server.stop();
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
    });
}

Or the same thing using guice:

public void startGuiceServer() {
    final NiftyBootstrap bootstrap = Guice.createInjector(
        Stage.PRODUCTION,
        new NiftyModule() {
            @Override
            protected void configureNifty() {
                // Create the handler
                MyService.Iface serviceInterface = new MyServiceHandler();

                // Create the processor
                TProcessor processor = new MyService.Processor<>(serviceInterface);

                // Build the server definition
                ThriftServerDef serverDef = new ThriftServerDefBuilder().withProcessor(processor)
                                                                        .build();

                // Bind the definition
                bind().toInstance(serverDef);
            }
        }).getInstance(NiftyBootstrap.class);

    // Start the server
    bootstrap.start();

    // Arrange to stop the server at shutdown
    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            bootstrap.stop();
        }
    });
}