入口
我们就拿nacos自己example下的NamingExample来做测试
public class NamingExample {
public static void main(String[] args) throws NacosException, InterruptedException {
Properties properties = new Properties();
properties.setProperty("serverAddr", "localhost");
properties.setProperty("namespace", "public");
NamingService naming = NamingFactory.createNamingService(properties);
naming.registerInstance("nacos.test.3", "11.11.11.11", 8888, "TEST1");
System.out.println("instances after register: " + naming.getAllInstances("nacos.test.3"));
Executor executor = new ThreadPoolExecutor( 1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(),
new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
Thread thread = new Thread(r);
thread.setName("test-thread");
return thread;
}
});
naming.subscribe("nacos.test.3", new AbstractEventListener() {
//EventListener onEvent is sync to handle, If process too low in onEvent, maybe block other onEvent callback.
//So you can override getExecutor() to async handle event.
@Override
public Executor getExecutor() {
return executor;
}
@Override
public void onEvent(Event event) {
System.out.println("serviceName: " + ((NamingEvent) event).getServiceName());
System.out.println("instances from event: " + ((NamingEvent) event).getInstances());
}
});
naming.deregisterInstance("nacos.test.3", "11.11.11.11", 8888, "TEST1");
Thread.sleep(1000);
System.out.println("instances after deregister: " + naming.getAllInstances("nacos.test.3"));
Thread.sleep(1000);
}
}
NamingFactory.createNamingService
�
将配置参数properties传进去,然后通过反射创建NamingService, 也就是说会调用到NacosNamingService的构造方法,我们来看一下
这里会调用到NamingClientProxyDelegate的构造方法
这里我们提前注意一下NamingGrpcClientProxy的构造方法,后面会用到
!!!有一个start方法,它会创建连接
connectToServer会调用到子类GrpcClient.connectToServer方法
naming.registerInstance
这里的namingServer是NacosNamingServer,最终会调用到NacosNamingServer.registerInstance(serviceName, ip, port, clusterName)
如果说group不传入的话,默认会设置一个DEFAULT_GROUP,继续调用
�
在构造方法里面我们能看到clientProxy实际上是一个NamingClientProxyDelegate,这里会调用它的registerService
NamingClientProxyDelegate.registerService
一般来说我们实例都是临时实例,所以这里使用的grpcClientProxy
接下来会调用到NamingGrpcClientProxy.registerService(serviceName, groupName, instance)
NamingGrpcClientProxy.registerService
- 又封装了一个InstanceRequest对象,里面包含namespaceId, serverName, groupName, instance等
- 调用requestToServer:向服务端发起请求了
这里的rpcClint是GrpcSdkClient,所以会调用到它的request方法
GrpcSdkClient.request
这里会调用到父类RpcClient.request方法
这里最终会调用到GrpcConnection里面的request方法
�