【发布时间】:2021-09-22 12:48:30
【问题描述】:
我正在尝试使用 NestJS 和 gRPC 构建微服务。它有两个服务,第一个是gRPC服务,第二个是调用gRPC服务的REST服务。
起初,它在单一调用 findRepoById rpc 上运行良好。但它不适用于服务器流式调用findAllReposrpc。当我尝试调用findAllRepos rpc 时会抛出这样的错误
UnhandledPromiseRejectionWarning: 错误: 12 UNIMPLEMENTED: 服务器没有实现方法findAllRepos
我写的文件如下所示
// main.proto
syntax = "proto3";
import "google/protobuf/timestamp.proto";
package main;
enum Visibility {
PUBLIC = 0;
PRIVATE = 1;
}
message Repository {
int32 id = 1;
string title = 2;
Visibility visibility = 3;
google.protobuf.Timestamp lastSeen = 4;
}
service MainService {
rpc findRepoById (RepoById) returns (Repository) {}
rpc findAllRepos (NoParam) returns (stream Repository) {}
}
message RepoById {
int32 id = 1;
}
message NoParam {}
// server.controller.ts
@Controller('repo')
export class RepoController {
constructor(
@Inject('RepoService') private readonly repoService: RepoService
) {}
@GrpcMethod('MainService', 'findRepoById')
findRepoById(request: RepoById, metadata: Metadata): Repository {
const targetId = request.id;
return this.repoService.findRepoById(targetId);
}
@GrpcStreamMethod('MainService', 'findAllRepos')
findAllRepos(request: NoParam, metadata: Metadata): Observable<Repository> {
const subject = new Subject<Repository>();
const repositories = this.repoService.findAllRepos();
repositories.map((repo) => {
subject.next(repo);
});
subject.complete();
return subject.asObservable();
}
}
// client.service.ts
export class RepoGrpcService implements OnModuleInit {
private mainService: MainServiceClient;
constructor(@Inject('main_package') private client: ClientGrpc) {}
onModuleInit() {
this.mainService = this.client.getService<MainServiceClient>('MainService');
}
findRepoById(id: number): Observable<Repository> {
return this.mainService.findRepoById({ id });
}
@GrpcStreamCall('MainService')
findAllRepos(): Observable<Repository[]> {
const results: Repository[] = [];
const repoStream = this.mainService.findAllRepos({});
repoStream.forEach((value) => console.log(value));
repoStream.subscribe({
next: (repo) => {
results.push(repo);
}
});
const subject = new Subject<Repository[]>();
subject.next(results);
subject.complete();
return subject.asObservable();
}
}
我想我已经遵循了与NestJS gRPC documentation 相同的所有代码,但不知何故它仍然不起作用。是不是我做错了什么?
【问题讨论】:
标签: protocol-buffers nestjs grpc grpc-node