最近项目上,用到了thrift技术,在我看来thrift就是起通讯作用,底层用的socket,实现客户端向服务端发送数据,它有一个很大的优势,可以兼容多种语言,如客户端可以用C#, 服务端用java,当然python,php等都是可以的。另外,也很简单。项目上用的是将卡口车辆数据,通过thrift,发送到服务器。
为了实现客户端与服务端分离,将其分为3个maven工程,一为thrift生成的公用工程,一为客户端程序,一为服务端程序。接下来将分别讲述。
1.公用工程
thrift有个生成类的工具,thrift.exe,需要在官网下载。另外还需要写一个后缀为thrift的通用的文件,通过该文件,可以生成各种语言的类,我建的文件名称为gender.thrift。
namespace java com.netposa.thrift
struct ViecleInfo{
1:i32 carNo,
2:string carPoll
}
service ThriftProxyService {
void uploadViecleInfo(ViecleInfo vi)
}
其中,namespace 后边接编程语言的名字,和所在的包名。 service相当于class的意思。然后在该文件夹下执行cmd命令:thrift.exe -r -gen java gender.thrift 即可生成2个类,分别为ViecleInfo和ThriftProxyService,将这2个类拷入建立的公用工程中,再打成jar包,供客户端程序,和服务端程序引用。
还有一个步骤,引入jar包。在客户端和服务端程序中,也需要引入该jar包。
<dependency>
<groupId>org.apache.thrift</groupId>
<artifactId>libthrift</artifactId>
<version>0.10.0</version>
</dependency>
2.客户端程序
首先通过maven引入刚生成的jar包:
<dependency>
<groupId>com.netposa</groupId>
<artifactId>thriftSDK</artifactId>
<version>0.0.1-SNAPSHOT</version>
<scope>system</scope>
<systemPath>${project.basedir}/lib/thriftSDK-0.0.1-SNAPSHOT.jar</systemPath>
</dependency>
客户端的端口,必须和服务端保持一致,此处设为9999,代码如下:
public static void main( String[] args ) throws TException
{
System.out.println("客户端启动:");
TTransport transport = null;
transport = new TSocket("172.16.91.139",9999,30000);
TProtocol protocol = new TBinaryProtocol(transport);
ThriftProxyService.Client client = new Client(protocol);
transport.open();
ViecleInfo data = generateViecle();
client.uploadViecleInfo(data);
}
private static ViecleInfo generateViecle(){
ViecleInfo info = new ViecleInfo();
info.carNo=123;
info.carPoll="whj's";
return info;
}
3.服务端程序
与客户端程序一样,先要导入本地jar,此处同上。然后建一个类实现Iface接口,在该实现类中,可以接收客户端传来的数据,并进行处理,具体代码如下:
import org.apache.thrift.TException;
import com.netposa.thriftSDK.ThriftProxyService.Iface;
import com.netposa.thriftSDK.ViecleInfo;
public class ThriftProxyImpl implements Iface {
public void uploadViecleInfo(ViecleInfo data) throws TException {
System.out.println("+++"+data.getCarNo()+" "+data.getCarPoll());
}
}
启动服务端thrift的代码如下:
public static void main( String[] args ) throws TTransportException
{
System.out.println( "server start:" );
TProcessor tprocessor = new ThriftProxyService.Processor<ThriftProxyService.Iface>(new ThriftProxyImpl());
TServerSocket serverTransport = new TServerSocket(9999);
TServer.Args tArgs = new TServer.Args(serverTransport);
tArgs.processor(tprocessor);
tArgs.protocolFactory(new TBinaryProtocol.Factory());
TServer server = new TSimpleServer(tArgs);
server.serve();
}