转载自 CSDN Arjick
Nifty是facebook公司开源的,基于netty的thrift服务端和客户端实现。然后使用此包就可以快速发布出基于netty的高效的服务端和客户端代码。
https://github.com/facebook/nifty
Nifty简单例子
1)环境搭建
pom文件
- <dependency>
- <groupId>com.facebook.nifty</groupId>
- <artifactId>nifty-core</artifactId>
- <version>0.9.0</version>
- </dependency>
- <dependency>
- <groupId>org.apache.thrift</groupId>
- <artifactId>libthrift</artifactId>
- <version>0.9.1</version>
- </dependency>
Thrift文件
- namespace java example // defines the namespace
- typedef i32 int //typedefs to get convenient names for your types
- service ThriftTestService {
- string test(1:string name),//delay 3s
- }
Server文件
- import java.util.concurrent.ExecutorService;
- import java.util.concurrent.Executors;
- import org.apache.thrift.TProcessor;
- import com.facebook.nifty.core.NettyServerTransport;
- import com.facebook.nifty.core.ThriftServerDef;
- import com.facebook.nifty.core.ThriftServerDefBuilder;
- import example.ThriftTestService;
- import example.ThriftTestServiceImpl;
- public class Server {
- /**
- * @param args
- */
- public static void main(String[] args) {
- // Create the handler
- ThriftTestService.Iface serviceInterface = new ThriftTestServiceImpl();
- // Create the processor
- TProcessor processor = new ThriftTestService.Processor<ThriftTestService.Iface>(
- serviceInterface);
- // Build the server definition
- ThriftServerDef serverDef = new ThriftServerDefBuilder().listen(7790)
- .withProcessor(processor).build();
- // Create the server transport
- final NettyServerTransport server = new NettyServerTransport(serverDef);
- // Start the server
- server.start();
- // 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();
- }
- }
- });
- System.out.println("服务器启动成功...");
- }
- }
- import org.apache.thrift.protocol.TBinaryProtocol;
- import org.apache.thrift.protocol.TProtocol;
- import org.apache.thrift.transport.TSocket;
- import org.apache.thrift.transport.TTransport;
- import example.ThriftTestService;
- public class Client {
- /**
- * @param args
- */
- public static void main(String[] args) throws Exception {
- TTransport transport = new TSocket("localhost", 7790);
- transport.open();
- TProtocol protocol = new TBinaryProtocol(transport);
- ThriftTestService.Client client = new ThriftTestService.Client(protocol);
- System.out.println(client.test("aa"));
- transport.close();
- }
- }