SpringBoot闆嗘垚gRPC鐨勬楠ゆ湁鍝簺
SpringBoot闆嗘垚gRPC鐨勬楠ゅ涓嬶細
- 娣诲姞渚濊禆锛氬湪SpringBoot椤圭洰鐨刾om.xml鏂囦欢涓坊鍔爂RPC鐨勪緷璧栵紝渚嬪锛?/li>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-netty</artifactId>
<version>1.41.0</version>
</dependency>
- 瀹氫箟.proto鏂囦欢锛氭牴鎹渶瑕佸畾涔塯RPC鎺ュ彛鐨?proto鏂囦欢锛屽苟浣跨敤protobuf缂栬瘧鍣ㄧ敓鎴愬搴旂殑Java绫伙紝渚嬪锛?/li>
syntax = "proto3";
package com.example;
service Greeter {
rpc SayHello (HelloRequest) returns (HelloReply) {}
}
message HelloRequest {
string name = 1;
}
message HelloReply {
string message = 1;
}
- 瀹炵幇Service锛氭牴鎹敓鎴愮殑Java绫诲疄鐜板搴旂殑Service鎺ュ彛锛屼緥濡傦細
@GrpcService
public class GreeterService extends GreeterGrpc.GreeterImplBase {
@Override
public void sayHello(HelloRequest request, StreamObserver<HelloReply> responseObserver) {
String message = "Hello " + request.getName();
HelloReply reply = HelloReply.newBuilder().setMessage(message).build();
responseObserver.onNext(reply);
responseObserver.onCompleted();
}
}
- 閰嶇疆Server锛氶厤缃甮RPC Server骞舵敞鍐屽疄鐜扮殑Service锛屼緥濡傦細
@Configuration
public class GrpcConfig {
@Bean
public Server grpcServer(List<BindableService> services) {
ServerBuilder<?> serverBuilder = ServerBuilder.forPort(9090);
services.forEach(serverBuilder::addService);
return serverBuilder.build();
}
}
- 鍚姩Server锛氬湪SpringBoot搴旂敤鐨勫惎鍔ㄧ被涓惎鍔╣RPC Server锛屼緥濡傦細
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
- 缂栧啓瀹㈡埛绔唬鐮侊細缂栧啓gRPC瀹㈡埛绔唬鐮佹潵璋冪敤鏈嶅姟绔帴鍙o紝渚嬪锛?/li>
public class GrpcClient {
public static void main(String[] args) {
ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", 9090)
.usePlaintext()
.build();
GreeterGrpc.GreeterBlockingStub stub = GreeterGrpc.newBlockingStub(channel);
HelloReply reply = stub.sayHello(HelloRequest.newBuilder().setName("World").build());
System.out.println(reply.getMessage());
channel.shutdown();
}
}
閫氳繃浠ヤ笂姝ラ锛屽氨鍙互瀹屾垚SpringBoot闆嗘垚gRPC鐨勫紑鍙戝伐浣溿€?/p>
相关问答