springboot " />

扫描二维码下载沐宇APP

沐宇

微信扫码使用沐宇小程序

沐宇

SpringBoot闆嗘垚gRPC鐨勬楠ゆ湁鍝簺

扬州沐宇科技
2024-06-13 17:51:45
springboot

SpringBoot闆嗘垚gRPC鐨勬楠ゅ涓嬶細

  1. 娣诲姞渚濊禆锛氬湪SpringBoot椤圭洰鐨刾om.xml鏂囦欢涓坊鍔爂RPC鐨勪緷璧栵紝渚嬪锛?/li>
<dependency>
    <groupId>io.grpc</groupId>
    <artifactId>grpc-netty</artifactId>
    <version>1.41.0</version>
</dependency>
  1. 瀹氫箟.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;
}
  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();
    }
}
  1. 閰嶇疆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();
    }
}
  1. 鍚姩Server锛氬湪SpringBoot搴旂敤鐨勫惎鍔ㄧ被涓惎鍔╣RPC Server锛屼緥濡傦細
@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}
  1. 缂栧啓瀹㈡埛绔唬鐮侊細缂栧啓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>

扫码添加客服微信