跳到主要内容

Connect

Connect 是基于 HTTP 的 RPC 协议,可使用 Protobuf 或 JSON 消息,适合浏览器和多语言客户端接入。

  • 支持普通请求响应、服务端流、客户端流和双向流。
  • 普通调用可使用 HTTP/1.1;双向流要求 HTTP/2。
  • 可绑定 .proto 文件,使用 Connect SDK 调用。

引入依赖​

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

启用协议​

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

提供者
configuration.connector("http")
.bind("127.0.0.1", 8080)
.protocol("connect").contextPath("/connect");
消费者
configuration.connector("http")
.protocol("connect")
.contextPath("/connect");

发起 RPC 调用​

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

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

public interface EchoService {
Message echo(@MetParam(id = 1) Message message);
}

public class Message {
@MetField(id = 1)
private String value;

public String getValue() { return value; }
public void setValue(String value) { this.value = value; }
}

public class EchoServiceImpl implements EchoService {
public Message echo(Message message) { return message; }
}
提供者
import net.hasor.meteor.protocol.grpc.GrpcProtoResource;

context.publisher().rsfService(EchoService.class, new EchoServiceImpl())
.name("meteor.example.EchoService")
.protocol("connect")
.bindResource("connect", GrpcProtoResource.load("classpath:echo.proto"))
.register();

将 echo.proto 放入 Meteor 提供者和消费者的 classpath 根目录;其他客户端使用同一文件生成消息类型:

echo.proto
syntax = "proto3";
package meteor.example;
option java_package = "example.generated";
option java_outer_classname = "EchoContract";
option go_package = "example.com/echo;echo";

message Message { string value = 1; }
service EchoService { rpc echo(Message) returns (Message); }
消费者
import net.hasor.meteor.address.InterAddress;
import net.hasor.meteor.protocol.grpc.GrpcProtoResource;

// 订阅服务接口
var binding = context.publisher().rsfService(EchoService.class)
.name("meteor.example.EchoService")
.protocol("connect")
.bindResource("connect", GrpcProtoResource.load("classpath:echo.proto"))
.register();

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

// 构造请求并调用服务
Message request = new Message();
request.setValue("hello");
System.out.println(client.echo(request).getValue());

协议配置​

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

  • serializeType:默认 Protobuf,也可选择 Json。
  • compression:默认 identity。
  • get=true:允许 GET 调用,仅适用于普通请求响应方法。
  • 流式调用启用 streamBody;双向流还需在连接器设置 httpVersion=2。

注意事项​

  • 基础地址后还需添加 .proto 中的完整服务名和方法名,通常由 SDK 完成。
  • 浏览器跨域调用需设置 CORS;携带凭据时使用明确的允许来源。
  • HTTP/1.1 普通调用成功不代表双向流配置已生效。