thrift使用(2):代码生成和接口调用

本文详细介绍如何使用Thrift进行RPC远程过程调用的整个流程,包括定义接口、生成代码、实现服务端与客户端交互等步骤,并提供了完整的示例代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. 编写接口thrift

namespace java com.wzz.thrift.result
struct Result   
{  
  1: string result,  
  2: map<string,string> value  
}  


namespace java com.wzz.thrift
include "Result.thrift"
 service FuzaServ{ 
  Result.Result helloWorld(1:string para)
}

2. 使用thrift.exe生成代码,


thrift-0.10.0.exe -gen java FuzaServ.thrift

thrift-0.10.0.exe -gen java Result.thrift


3. 看到已经生成了代码,在文件夹下

将代码复制到eclipse中,开始写实现类
public class FuzaServImpl implements Iface{

	@Override
	public Result helloWorld(String para) throws TException {
		System.out.println(para);
		Result r = new Result();
		return r;
	}

}

4. 发布服务,编写服务端的代码
public class Server {
	public static void main(String[] args) throws TTransportException {
		TServerSocket serverTransport = new TServerSocket(7911);//设置服务器端口
        Factory proFactory = new TBinaryProtocol.Factory();//设置协议工厂
        TProcessor processor = new FuzaServ.Processor<FuzaServ.Iface>(new FuzaServImpl());//关联处理器与Hello.thrift文件中定义的服务的实现
        TServer.Args tArgs = new TServer.Args(serverTransport);
        tArgs.processor(processor);
        tArgs.protocolFactory(proFactory);
        
        TServer server = new TSimpleServer(tArgs);
        System.out.println("Start server on port 7911");
        server.serve();
	}
}

5. 接口调用

public class Client {

	public static void main(String[] args) throws TException {
		TTransport transport = new TSocket("localhost", 7911);// 建立连接
		transport.open();
		TProtocol protocol = new TBinaryProtocol(transport);
		FuzaServ.Client client = new FuzaServ.Client(protocol);// 生成客户端实例对象
		Result helloWorld = client.helloWorld("hello");
	}

}

另附:

pom文件,引入包
<dependency>
			<groupId>org.apache.thrift</groupId>
			<artifactId>libthrift</artifactId>
			<version>0.10.0</version>
		</dependency>





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值