基于Thrift WebService实现的JavaSe项目

Thrift 之前属于facebook,2007年提交给Apache。目前版本为0.9.1,采用Ant管理。在成功的构建之后会有libthrift-0.9.1.jar 。是其java实现。Thrift的诱人之处在于跨平台,类http的rmp协议在性能上有明显的优势。

除了libthrift-0.9.1.jar 外,在Windows下开发还需要thrift-0.9.1.exe编译工具。


现在完成一个简单的Java标准项目,其中包含其服务端和客户端。


1.编写一个book.thrift文件,这是一个使用接口定义语言 (interface definition language,IDL) 来定义数据类型和服务的文件。

namespace java com.oran.thrift.dao

service BookService{
	string buyBook(1:string bookName)
}


2.使用编译工具生成java文件,命令为:


thrift-0.9.1.exe -r -gen java book.thrift

生成的Java文件缩略图为:


将这个接口文件拷贝到对应的package下面。


3.实现接口BookService.Iface:


public class BookServiceImpl implements com.oran.thrift.dao.BookService.Iface {

	@Override
	public String buyBook(String bookName) throws TException {
		System.out.println("bookName = " + bookName);
		return bookName+" 我买了...";
	}

}


现在开始应用这个实现.


4.服务端实现:

package com.oran.test.main;

import org.apache.thrift.TProcessor;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.server.TServer;
import org.apache.thrift.server.TSimpleServer;
import org.apache.thrift.transport.TServerSocket;
import org.apache.thrift.transport.TTransportException;

import com.oran.thrift.dao.BookService;
import com.oran.thrift.dao.impl.BookServiceImpl;

public class RunServer {
	private static final int SERVER_PORT = 8090;
	
	public static void main(String[] args) throws TTransportException {
		
		System.out.println("BookService is running...");
		TProcessor processor = new BookService.Processor<BookService.Iface>(new BookServiceImpl());
		TServerSocket serverSocket = new TServerSocket(SERVER_PORT);
		TServer.Args tArgs = new TServer.Args(serverSocket);
		tArgs.processor(processor);
		tArgs.protocolFactory(new TBinaryProtocol.Factory());
		
		TServer tServer = new TSimpleServer(tArgs);
		tServer.serve();
	}
}


5.客户端实现:

package com.oran.test.main;

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 com.oran.thrift.dao.BookService;

public class RunClient {
	public static final String SERVER_IP = "localhost" ;
	public static final int SERVER_PORT = 8090 ;
	public static final int TIMEOUT = 30000 ;
	
	public static void main(String[] args) {
		TTransport transport = null;
		try{
			transport = new TSocket(SERVER_IP, SERVER_PORT, TIMEOUT);
			TProtocol protocol = new TBinaryProtocol(transport);
			BookService.Client client = new BookService.Client(protocol);
			transport.open();
			String result = client.buyBook("老人与海");
			System.out.println("THRIFT RETURN = "+result);
		}catch(Exception e){
			
		}
	}
}

OK,代码部分完毕。


<!-- 服务端结果 -->
BookService is running...

<!-- 客户端结果 -->
THRIFT RETURN = 老人与海 我买了...



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值