gRPC-Web

gRPC for Web Clients

A JavaScript implementation of gRPC for browser clients.

浏览器端的GRPC客户端,JS编写。

https://github.com/grpc/grpc-web/

 

云原生计算基金会(CNCF)正式发布 GA 版本的 gRPC-Web,这是一个 JavaScript 客户端库,使 Web 应用程序能够直接与后端 gRPC 服务通信,不需要 HTTP 服务器充当中介。

    与 REST 的区别
    gRPC:一个客户端应用程序通过 Protocol Buffers 与一个 gRPC 后端服务器通信,然后这个服务器也通过 Protocol Buffers 与其他的 gRPC 后端服务器通信。
    REST:Web 应用程序通过 HTTP 与后端 REST API 服务器通信,然后这个服务器又通过 Protocol Buffers 与其他后端服务通信。


    产生的原因
    gRPC是一个基于HTTP/2实现的高性能远程过程调用框架,但是由于浏览器没有直接暴露HTTP/2,所以Web应用程序不能直接使用gRPC。gRPC-Web是一个标准化协议,它解决了这个问题,可以在浏览器中使用gRPC。
   

 

 



    JS中使用gRPC
    Windows系统在JS中使用.proto文件需要有.protoc-gen-grpc-web.exe(生成web js文件的工具)、protoc.exe(Protocol Buffers工具)和.proto文件,在使用时需要npm安装grpc-web。之后执行如下命令即可:

// 会生成{proto_name}_pb.js和{proto_name}_grpc_pb.js
{路径}protoc -I=./ {路径下的proto文件} --js_out=import_style=commonjs:./ --plugin=protoc-gen-grpc={路径}/protoc-gen-grpc-web.exe --grpc-web_out=import_style=commonjs,mode=grpcwebtext:./

    1
    2

在Vue中使用gRPC Client示例如下,向后台发起register的gRPC请求:

import * as grpc_web from '../proto/admin_grpc_web_pb'
import {AdminClient} from '../proto/admin_grpc_web_pb'

export const rpcWeb = grpc_web
export const client = new AdminClient('http://127.0.0.1:8081')
----------------------------------------
let send = new rpcWeb.registerRequest()
send.setName('huang')
...
const metaData = {authorization: '...'}

// client.register(registerRequest, metadata, (err,response)=>{})
client[register](send, metaData, (err, resp) => {
    ...
}

// service端代码参考:https://github.com/grpc/grpc-web/blob/master/net/grpc/gateway/examples/echo/node-server/server.js



JS中使用.proto文件教程
————————————————
版权声明:本文为CSDN博主「木瓜有益健康」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/Papaya_shun/article/details/108279534
posted @ 2022-06-13 23:29  jiftle  阅读(694)  评论(0编辑  收藏  举报