> anoyi中的GrpcServer
1. 查看屬性
~~~
private final GrpcProperties grpcProperties;
private final CommonService commonService;
private ServerInterceptor serverInterceptor;
private Server server;
~~~
grpcProperties是服務端的屬性,包含端口,CommonService 是繼承了proto協議生成CommonServiceGrpc的CommonServiceImplBase這個類,并重寫了handle這個接收請求的方法,實現基層通訊,serverInterceptor是攔截器,也就是token,令牌等的使用,Server是grpc的類,是服務端的基礎請求封裝
2. 構造方法(自己看)
~~~
public GrpcServer(GrpcProperties grpcProperties, CommonService commonService) {
this.grpcProperties = grpcProperties;
this.commonService = commonService;
}
public GrpcServer(GrpcProperties grpcProperties, CommonService commonService, ServerInterceptor serverInterceptor) {
this.grpcProperties = grpcProperties;
this.commonService = commonService;
this.serverInterceptor = serverInterceptor;
}
~~~
3. 重要方法
~~~
/**
* 啟動服務
* @throws Exception 異常
*/
public void start() throws Exception{
int port = grpcProperties.getPort();
if (serverInterceptor != null){
server = ServerBuilder.forPort(port).addService(ServerInterceptors.intercept(commonService, serverInterceptor)).build().start();
}else {
Class clazz = grpcProperties.getServerInterceptor();
if (clazz == null){
server = ServerBuilder.forPort(port).addService(commonService).build().start();
}else {
server = ServerBuilder.forPort(port).addService(ServerInterceptors.intercept(commonService, (ServerInterceptor) clazz.newInstance())).build().start();
}
}
log.info("gRPC Server started, listening on port " + server.getPort());
startDaemonAwaitThread();
}
~~~
ServerBuilder其實就是一個builder,ServerInterceptors可以把攔截器綁定到通道,接下來看看這個方法
```
server = ServerBuilder.forPort(port).addService(ServerInterceptors.intercept(commonService, serverInterceptor)).build().start();
```
這個方法意思是綁定端口,綁定攔截器生成grpc的server,接下來看看startDaemonAwaitThread();
~~~
private void startDaemonAwaitThread() {
Thread awaitThread = new Thread(()->{
try {
GrpcServer.this.server.awaitTermination();
} catch (InterruptedException e) {
log.warn("gRPC server stopped." + e.getMessage());
}
});
awaitThread.setDaemon(false);
awaitThread.start();
}
~~~
這個方法其實是綁定線程,啟動服務端,這樣grpc課程基本結束了,具體怎么樣,自己去摸索,我會提供github代碼
[https://github.com/ChinaSilence/spring-boot-starter-grpc](https://github.com/ChinaSilence/spring-boot-starter-grpc)