Thrift交流(二)thrift服务端和客户端实现 Nifty

来源:互联网 发布:淘宝法国灰太太正品吗 编辑:程序博客网 时间:2024/05/01 17:58
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 handlerThriftTestService.Iface serviceInterface = new ThriftTestServiceImpl();// Create the processorTProcessor processor = new ThriftTestService.Processor<ThriftTestService.Iface>(serviceInterface);// Build the server definitionThriftServerDef serverDef = new ThriftServerDefBuilder().listen(7790).withProcessor(processor).build();// Create the server transportfinal NettyServerTransport server = new NettyServerTransport(serverDef);// Start the serverserver.start();// Arrange to stop the server at shutdownRuntime.getRuntime().addShutdownHook(new Thread() {@Overridepublic void run() {try {server.stop();} catch (InterruptedException e) {Thread.currentThread().interrupt();}}});System.out.println("服务器启动成功...");}}
Client

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();}}






0 0
原创粉丝点击