Skip to main content

This page is available in Simplified Chinese.

gRPC-Web

gRPC-Web 面向浏览器,通过浏览器可使用的 HTTP 请求调用 Protobuf 服务。Meteor 可直接提供 gRPC-Web 接入点。

  • 支持普通请求响应和服务端流。
  • 支持二进制和 Text 两种消息格式。
  • 不支持客户端流和双向流。

引入依赖​

gRPC-Web 与 gRPC 使用同一个协议模块。

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

启用协议​

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

提供者
configuration.connector("http")
.bind("127.0.0.1", 8080)
.protocol("grpc-web").contextPath("/grpc-web")
.option("corsOrigins", "http://127.0.0.1:8090,http://localhost:8090");
消费者
configuration.connector("http")
.protocol("grpc-web")
.contextPath("/grpc-web");

发起 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("grpc-web")
.bindResource("grpc-web", 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("grpc-web")
.bindResource("grpc-web", GrpcProtoResource.load("classpath:echo.proto"))
.register();

// 通过直连地址获取代理
EchoService client = context.getRsfClient(new InterAddress("grpc-web", "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.grpc-web.options.<名称>。

  • webText:默认 false,使用二进制格式;设为 true 使用 Text 格式。
  • corsOrigins、corsHeaders:默认 *。
  • corsCredentials:默认 false;corsMaxAge:默认 600 秒。

注意事项​

  • 普通 gRPC 客户端不能直接替代 gRPC-Web 客户端。
  • 客户端格式与服务端 webText 配置应一致。
  • 携带浏览器凭据时,必须配置明确的允许来源,不能使用 *;代理需正确转发 OPTIONS 预检请求。