Thrift安装与使用
jopen
9年前
代码示例
-
thrift转Java: thrift-0.9.1.exe -r -gen java ./demoHello.thrift
-
实现服务端接口( 接口实现类 )
public class HelloWorldImpl implements HelloWorldService.Iface{ private static final Logger logger = Logger.getLogger(HelloWorldImpl.class); @Override public String sayHello(String username) throws TException { return "Hi,"+username+" welcome to my Server...."; } }
-
编写服务端
public class HelloServerDemo { public static final int SERVER_PORT = 8090; private static final Logger logger = Logger.getLogger(HelloServerDemo.class); public static void main(String[] args){ HelloServerDemo serverDemo = new HelloServerDemo(); serverDemo.startServer(); } public void startServer(){ // TServer --> TServer.Args: 1. TServerSocket( port ) // 2. interface // 3. TBinaryProtocol.Factory() try { System.out.println("HelloWorld TSimpleServer start...."); //TProcessor tProcessor = new HelloWorldService.Processor<HelloWorldService.Iface>(new HelloWorldImpl()); HelloWorldService.Processor<HelloWorldService.Iface> tprocessor = new HelloWorldService.Processor<HelloWorldService.Iface>(new HelloWorldImpl()); //简单地单线程服务模型,一般用于测试 TServerSocket serverTransport = new TServerSocket(SERVER_PORT); TServer.Args tArgs = new TServer.Args(serverTransport); tArgs.processor(tprocessor); tArgs.protocolFactory(new TBinaryProtocol.Factory()); //tArgs.protocolFactory(new TCompactProtocol.Factory()); //tArgs.protocolFactory(new TJSONProtocol.Factory()); TServer server = new TSimpleServer(tArgs); server.serve(); } catch (TTransportException e) { e.printStackTrace(); } } }
-
编写Client
public class HelloClientDemo { public static final String SERVER_IP = "localhost"; public static final int SERVER_PORT = 8090; public static final int TIME_OUT = 30000; public static void main(String[] args){ try { new HelloClientDemo().startClient("Tanzhen"); } catch (TException e) { e.printStackTrace(); } } public static void startClient(String usrname) throws TException { TTransport transport = null; transport = new TSocket(SERVER_IP,SERVER_PORT,TIME_OUT); TProtocol protocol = new TBinaryProtocol(transport); HelloWorldService.Client client = new HelloWorldService.Client(protocol); transport.open(); String result = client.sayHello(usrname); System.out.println("Thrift client result="+result); } }
基本类型
-
bool: 布尔值,true或false,对应Java的boolean
-
byte:8位有符号数,对应Java的byte
-
i16:16位有符号数,对应Java的short
-
i32:32位有符号数,对应Java的int
-
i64:对应Java的long
-
double:对应Java的double
-
string:utf-8编码的字符串,对应Java的String
-
list:对应Java中ArrayList
-
set:对应Java的HashSet
-
map:对应Java的HashMap
-
exception:对应Java的Exception
-
service:对应服务的类
结构体
-
struct:定义公共对象,类似于C语言中的结构体定义,在Java中是一个JavaBean
原理详解
http://www.cnblogs.com/brucewoo/archive/2012/06/03/2532788.html
是什么:
为什么:
怎么做: