js客户端grpc调用服务器

使用micro创建了一个hello空白工程并运行后, 就想着用nodejs编写一个客户端

如果能成功调用, 那就说明micro完全可用

服务端

创建并运行hello

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# 根据自建micro创建容器
docker run -d -it --name hello micro /bin/bash

# 进入容器
docker exec -it hello /bin/bash

# 启动服务
nohup micro server &

# 登录服务
micro login --username admin --password micro

# 创建新的应用
micro new hello

cd hello

# 生成proto
make proto

# 运行服务
micro run .

客户端

micro

1
micro hello call --name cyl

curl

1
curl "http://localhost:8080/hello?name=cyl"

nodejs http

根据 curl 请求地址 得

1
2
3
4
5
6
const http = require("http")
http.get("http://localhost:8080/hello?name=cyl", rsp => {
let data = ""
rsp.on("data", chunk => data += chunk)
rsp.on("end", () => console.log(JSON.parse(data)))
})

nodejs grpc

  • 修改proto地址

  • 修改端口: 根据启动日志 micro logs hello 查看hello的grpc监听端口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
const grpc = require('@grpc/grpc-js')
const protoLoader = require('@grpc/proto-loader')

const protoPath = "proto/hello.proto"
const proto = grpc.loadPackageDefinition(protoLoader.loadSync(protoPath, { keepCase: true, longs: String, enums: String, defaults: true, oneofs: true }))
const client = new proto.hello.Hello('localhost:34067', grpc.credentials.createInsecure())

// call
for (let i = 0; i < 5; i++) {
let time = Date.now()
client.call({ name: "cyl" }, (err, response) => {
console.log("call data t:", Date.now() - time, response)
})
}

// stream
let streamTime = Date.now()
const stream = client.stream({ count: 5 })
stream.on('data', response => {
console.log("stream data t:", Date.now() - streamTime, response)
streamTime = Date.now()
})
stream.on('end', () => {
console.log("stream end t:", Date.now() - streamTime)
})

// pingPong
const pingPong = client.pingPong()
let pingPongTime
const sendPingPong = () => {
pingPongTime = Date.now()
pingPong.write({ stroke: pingPongTime })
}
pingPong.on('data', response => {
console.log("pingPong data t:", Date.now() - pingPongTime, response)
setTimeout(sendPingPong, 1000)
})
sendPingPong()

得到日志截图

grpc耗时

grpc调用耗时情况

名称 描述 第一次 后续平均
call 单个请求 42ms 49.6ms
stream 服务端流 49ms 0.4ms
pingPong 双端流 48ms 0.83ms
  • 平均的第一次来回耗时 49ms

  • 但流连通后就非常快 不到 1ms