http://blog.zhengdong.me/2012/05/10/hello-world-by-thrift-using-java/
demo.thrift 文件内容如下
namespace java com.vv.test
struct Item {
1: i64 id,
2: string content,
}
service CrawlingService {
void write(1:list<Item> items),
}
使用命令自动生成文件
F:\>thrift-0.10.0.exe --gen java demo.thrift
然后拷贝到项目
然后编写样例代码
- import java.util.ArrayList;
- import java.util.List;
- import org.apache.thrift.TException;
- import org.apache.thrift.protocol.TBinaryProtocol;
- import org.apache.thrift.protocol.TProtocol;
- import org.apache.thrift.server.TServer;
- import org.apache.thrift.server.TThreadPoolServer;
- import org.apache.thrift.transport.TServerSocket;
- import org.apache.thrift.transport.TSocket;
- import org.apache.thrift.transport.TTransport;
- import org.apache.thrift.transport.TTransportException;
- import com.vv.test.CrawlingService;
- import com.vv.test.Item;
- public class T {
- public static void main(String[] args) throws InterruptedException {
- new Thread(new Server()).start();
- Thread.sleep(1000);
- Client client = new Client();
- List<Item> list = new ArrayList<Item>();
- for (int i = 1; i <= 10; i++) {
- Item item = new Item();
- item.setId(i);
- item.setContent("hello world " + i);
- list.add(item);
- }
- client.write(list);
- }
- }
- class Server implements Runnable {
- @Override
- public void run() {
- try {
- // Set port
- TServerSocket serverTransport = new TServerSocket(9090);
- // Set CrawlingHandler we defined before
- // to processor, which handles RPC calls
- // Remember, one service per server
- CrawlingHandler handler = new CrawlingHandler();
- CrawlingService.Processor<CrawlingService.Iface> processor = new CrawlingService.Processor<CrawlingService.Iface>(
- handler);
- TServer server = new TThreadPoolServer(new TThreadPoolServer.Args(serverTransport).processor(processor));
- System.out.println("Starting server on port 9090 ...");
- server.serve();
- } catch (TTransportException e) {
- e.printStackTrace();
- }
- }
- }
- class Client {
- public void write(List<Item> items) {
- TTransport transport;
- try {
- transport = new TSocket("localhost", 9090);
- transport.open();
- TProtocol protocol = new TBinaryProtocol(transport);
- CrawlingService.Client client = new CrawlingService.Client(protocol);
- client.write(items);
- transport.close();
- } catch (TTransportException e) {
- e.printStackTrace();
- } catch (TException e) {
- e.printStackTrace();
- }
- }
- }
- class CrawlingHandler implements CrawlingService.Iface {
- @Override
- public void write(List<Item> items) throws TException {
- for (Item item : items) {
- System.out.println(item);
- }
- };
- }
执行结果如下:
但是输出的最后一行显示"Received 1" ,这个输出是从哪里来的?以后慢慢再看吧.
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/29254281/viewspace-2135577/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/29254281/viewspace-2135577/