Va5*_*li5 6 node.js google-cloud-platform grpc grpc-node google-cloud-run
刚接触 Google Cloud Run 并尝试让两个 node.js 微服务通过 gRPC 进行内部通信。
客户端界面:
constructor(address: string, credentials: grpc.ChannelCredentials, options?: object);
Run Code Online (Sandbox Code Playgroud)
客户端代码:
const client: MyClient = new MyClient('my-service-abcdefgh3a-ew.a.run.app:443', grpc.credentials.createSsl());
Run Code Online (Sandbox Code Playgroud)
服务器代码:
const server = new grpc.Server();
server.addService<IMyServer>(MyService, new MyServer());
server.bind(`0.0.0.0:${process.env.PORT}`, grpc.ServerCredentials.createInsecure());
server.start();
Run Code Online (Sandbox Code Playgroud)
服务器设置为侦听 443。
当服务对公共请求开放时,上述内容似乎有效,但当您将服务器设置为内部时则无效。有任何想法吗?
您必须在请求元数据中添加凭据。这是一个例子
...
// Create a client for the protobuf spec
const client = new protoObj.Greeter(HOST, grpc.credentials.createInsecure());
// Build gRPC request
const metadata = new grpc.Metadata();
metadata.add('authorization', `Bearer ${JWT_AUTH_TOKEN}`);
// Execute gRPC request
client.sayHello({name: GREETEE}, metadata, (err, response) => {...
Run Code Online (Sandbox Code Playgroud)
第二个问题,如何获取JWT_AUTH_TOKEN。这里是 Cloud Run 的文档来执行此操作。但不完全是这样,只需获取令牌并在请求的元数据中使用它
...
request(tokenRequestOptions)
.then((token) => {
// add the token to the metadata
});
// Make the call
...
Run Code Online (Sandbox Code Playgroud)