05-Spring Cloud Alibaba Nacos注册中心GRPC总结
在Spring Cloud Alibaba中使用Nacos作为服务注册中心时,可以通过GRPC协议进行服务间通信。以下是一个使用GRPC的简单示例:
- 添加依赖:
<dependencies>
<!-- Spring Cloud Alibaba Nacos Discovery -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<!-- GRPC -->
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-netty-shaded</artifactId>
<version>${grpc.version}</version>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-protobuf</artifactId>
<version>${grpc.version}</version>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-stub</artifactId>
<version>${grpc.version}</version>
</dependency>
</dependencies>
- 服务端定义gRPC服务:
public class GreeterService extends GreeterGrpc.GreeterImplBase {
@Override
public void sayHello(HelloRequest req, StreamObserver<HelloReply> responseObserver) {
HelloReply reply = HelloReply.newBuilder().setMessage("Hello " + req.getName()).build();
responseObserver.onNext(reply);
responseObserver.onCompleted();
}
}
- 启动gRPC服务端,并注册到Nacos:
@SpringBootApplication
@EnableDiscoveryClient
public class GrpcServerApplication {
public static void main(String[] args) throws IOException, InterruptedException {
SpringApplication.run(GrpcServerApplication.class, args);
// 服务端启动后注册服务到Nacos
TimeUnit.SECONDS.sleep(10);
// 做一些服务注册之后的操作
}
@Bean
public Server grpcServer(GrpcProperties grpcProperties) throws IOException {
int port = grpcProperties.getPort();
Server server = ServerBuilder.forPort(port)
.addService(new GreeterService())
.build()
.start();
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
System.err.println("*** shutting down gRPC server since JVM is shutting down");
try {
server.shutdown().awaitTermination(30, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace(System.err);
Thread.currentThread().interrupt();
}
System.err.println("*** server shut down");
}));
return server;
}
}
- 客户端通过Nacos获取服
评论已关闭