gRPC Java客户端发送请求报错:Builder无法转换为SentenceClassificationRequest
问题根因
你使用Protobuf Builder构造请求对象时缺少了build()方法调用,newBuilder()返回的是SentenceClassificationRequest.Builder类型的构造器实例,而非最终的SentenceClassificationRequest请求实例,所以传入gRPC调用方法时触发类型不匹配错误。
修正方案
修改请求构造行,在参数设置完成后追加build()方法调用即可,修正后的完整代码如下:
ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", 9090).usePlaintext().build(); SentenceClassificationServiceGrpc.SentenceClassificationServiceBlockingStub SentenceClassificationStub = SentenceClassificationServiceGrpc.newBlockingStub(channel); SentenceClassificationRequest request = SentenceClassificationRequest.newBuilder().setDocument("hey").setThreshold(1).build(); SentenceClassificationResponse response = SentenceClassificationStub.classification(request);
补充说明
- Protobuf生成的Java类均遵循Builder构造模式,所有参数设置完成后必须调用
build()才能生成最终的实体实例,Builder实例本身不能直接作为请求/响应参数传递 - 如果需要复用相同参数构造多个请求,可以先保存Builder实例,多次调用
build()生成多个独立的请求对象
内容的提问来源于stack exchange,提问作者Berto
相关产品推荐
相关产品推荐

