????????nacos2.x与nacos1.x在性能上有了蛮大提升,作为配置中心使用时nacos2.x支持通过长连接的方式工作,当配置更改后将新的配置推送到nacos config客户端(springboot应用等)。
? ? ? ? nacos作为配置中心的使用方法可以参考nacos官网:Nacos Spring Cloud 快速开始,这里就不再赘述使用方法,仅说明下nacos2.x在作为配置中心时需要注意的地方,,
Nacos2.0.x版本相比1.X新增了gRPC的通信方式,因此需要增加2个端口。新增端口是在配置的主端口(server.port)基础上,进行一定偏移量自动生成。
端口 | 与主端口的偏移量 | 描述 |
---|
9848 | 1000 | 客户端gRPC请求服务端端口,用于客户端向服务端发起连接和请求 | 9849 | 1001 | 服务端gRPC请求服务端端口,用于服务间同步等 |
所以如果使用nacos-client 2.0.1版本,必须保证nacos server对应的9849端口开发,在使用docker或者k8s部署nacos-server时需要将对应的端口暴漏出来,特别需要注意的是k8s环境,k8s默认端口开放范围为30000-32768,使用kubesphere部署时对外暴露的NodePort端口是随机生成的,这时我们就需要对其进行修改,保证对外暴露端口相差1000,如下图所示:
这部分可以在
com.alibaba.nacos.common.remote.client.grpc.GrpcClient的connectToServer方法中找到:
@Override
public Connection connectToServer(ServerInfo serverInfo) {
try {
if (grpcExecutor == null) {
int threadNumber = ThreadUtils.getSuitableThreadCount(8);
grpcExecutor = new ThreadPoolExecutor(threadNumber, threadNumber, 10L, TimeUnit.SECONDS,
new LinkedBlockingQueue<>(10000),
new ThreadFactoryBuilder().setDaemon(true).setNameFormat("nacos-grpc-client-executor-%d")
.build());
grpcExecutor.allowCoreThreadTimeOut(true);
}
// 创建与nacos-server的grpc连接,端口号为8848(docker环境暴露则为对外暴露端口,比如本文中的31648端口)+端口偏移(1000)
RequestGrpc.RequestFutureStub newChannelStubTemp = createNewChannelStub(serverInfo.getServerIp(),
serverInfo.getServerPort() + rpcPortOffset());
if (newChannelStubTemp != null) {
Response response = serverCheck(newChannelStubTemp);
if (response == null || !(response instanceof ServerCheckResponse)) {
shuntDownChannel((ManagedChannel) newChannelStubTemp.getChannel());
return null;
}
BiRequestStreamGrpc.BiRequestStreamStub biRequestStreamStub = BiRequestStreamGrpc
.newStub(newChannelStubTemp.getChannel());
GrpcConnection grpcConn = new GrpcConnection(serverInfo, grpcExecutor);
grpcConn.setConnectionId(((ServerCheckResponse) response).getConnectionId());
//create stream request and bind connection event to this connection.
StreamObserver<Payload> payloadStreamObserver = bindRequestStream(biRequestStreamStub, grpcConn);
// stream observer to send response to server
grpcConn.setPayloadStreamObserver(payloadStreamObserver);
grpcConn.setGrpcFutureServiceStub(newChannelStubTemp);
grpcConn.setChannel((ManagedChannel) newChannelStubTemp.getChannel());
//send a setup request.
ConnectionSetupRequest conSetupRequest = new ConnectionSetupRequest();
conSetupRequest.setClientVersion(VersionUtils.getFullClientVersion());
conSetupRequest.setLabels(super.getLabels());
conSetupRequest.setAbilities(super.clientAbilities);
conSetupRequest.setTenant(super.getTenant());
grpcConn.sendRequest(conSetupRequest);
//wait to register connection setup
Thread.sleep(100L);
return grpcConn;
}
return null;
} catch (Exception e) {
LOGGER.error("[{}]Fail to connect to server!,error={}", GrpcClient.this.getName(), e);
}
return null;
}
?所以要想通过nacos-client2.0.1与nacos-server通信,需要对外暴露8848以及9848端口
注意:
一定要保证docker容器对外暴露端口满足1000,1001的关系
参考文章:
1、https://nacos.io/zh-cn/docs/2.0.0-compatibility.html
|