-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.ts
56 lines (43 loc) · 1.49 KB
/
app.ts
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
'use strict';
const PROTO_FILE_PATH = __dirname + '/app/proto/hello.proto'; // proto文件位置
const PORT = ':50051'; // RPC服务端端口
const grpc = require('grpc');
const protoLoader = require('@grpc/proto-loader');
'use strict';
import * as path from 'path';
import { Application } from 'egg';
export default (app: Application) => {
/**
* 应用启动前初始化工作
*/
app.beforeStart(async () => {
app['tips'] = 'tomato-log start...';
console.log(app['tips']);
// 新建一个grpc服务器
const server = new grpc.Server();
// 异步加载服务
await protoLoader.load(PROTO_FILE_PATH).then(packageDefinition => {
// 获取proto
const helloProto = grpc.loadPackageDefinition(packageDefinition);
// 获取package
const grpc_demo = helloProto.demo;
// 定义HelloService的SayHello实现
const sayHello = (call, callback) => {
// 打印客户端请求内容
console.log(call.request);
// 响应客户端
callback(null, {
code: '0',
message: '来自Node服务端的OK',
});
};
// 将sayHello方法作为HelloService的实现放入grpc服务器中
server.addService(grpc_demo.HelloService.service, { sayHello });
});
// 启动服务监听
server.bind(`0.0.0.0${PORT}`, grpc.ServerCredentials.createInsecure());
server.start();
});
const directory = path.join(app.config.baseDir, 'app/util');
app.loader.loadToApp(directory, 'util');
};