ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
> 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)