Skip to main content

This page is available in Simplified Chinese.

Thrift

Thrift 使用接口定义文件描述方法和消息,可生成多种语言的客户端,适合已有 Thrift 系统接入。

  • 支持 TCP 和 HTTP,协议名分别为 thrift、thrift-http。
  • 支持 Binary、Compact、JSON 编码及 framed、unframed 传输。
  • 支持普通请求响应和 oneway,不支持流式调用。

引入依赖​

<dependency>
<groupId>net.hasor</groupId>
<artifactId>meteor-protocol-thrift</artifactId>
<version>5.0.0-SNAPSHOT</version>
</dependency>

启用协议​

提供者监听端口并提供服务,消费者通过出站协议调用服务。

提供者
configuration.connector("tcp")
.bind("127.0.0.1", 8080)
.protocol("thrift");
消费者
configuration.connector("tcp")
.protocol("thrift");

发起 RPC 调用​

在已启动的 MetContext 中发布 EchoService,客户端调用 echo,输出 hello。

服务定义
import net.hasor.meteor.annotation.MetParam;

public interface EchoService {
String echo(@MetParam(id = 1) String text);
}

public class EchoServiceImpl implements EchoService {
public String echo(String text) { return text; }
}
提供者
context.publisher().rsfService(EchoService.class, new EchoServiceImpl())
.name("meteor.example.EchoService")
.protocol("thrift")
.aliasName("thrift", "EchoService")
.register();

客户端使用 echo.thrift 生成代码:

echo.thrift
namespace java example.generated
namespace py echo
namespace go echo

service EchoService { string echo(1: string text) }

使用 Thrift 0.25.0 编译器生成客户端代码。

消费者
import net.hasor.meteor.address.InterAddress;

// 订阅服务接口
var binding = context.publisher().rsfService(EchoService.class)
.name("meteor.example.EchoService")
.protocol("thrift")
.aliasName("thrift", "EchoService")
.register();

// 通过直连地址获取代理
EchoService client = context.getRsfClient(new InterAddress("thrift", "127.0.0.1", 8080))
.getRemote(binding);

// 调用服务
System.out.println(client.echo("hello"));

协议配置​

已有 IDL 使用 ThriftIdlResource.load("classpath:echo.thrift") 加载,通过 bindResource("thrift", resource) 绑定。

通过 protocol.option("名称", 值) 设置协议选项;配置文件使用 meteor.connectors.thrift.options.<名称>。

  • encoding:默认 binary,可选 compact、json。
  • framed:默认 true。
  • multiplexed:默认 false;启用后客户端也需配置服务名。
  • maxMessageSize、maxContainerSize、maxDepth:限制消息及嵌套数据。

注意事项​

  • 两端的编码、分帧方式、字段编号和方法名须一致。
  • oneway 方法必须返回 void 且不声明异常。
  • HTTP 使用 connector("http").protocol("thrift-http");接口资源也按 thrift-http 绑定。