【Eureka】【源码+图解】【六】Eureka的续约功能
目录
- 6. 下线
- 6.1 shutdown()
- 6.2 服务端cancel
- 6.3 同步其他server节点
6. 下线
主动下线方式
服务端:/eureka/apps/{application.name}/{instance-id},以本系列文章的helloworld为例,发送DELETE请求http://localhost:3333/eureka/apps/MY-EUREKA-CLIENT/localhost:my-eureka-client:2222
便可将客户端实例下线
客户端:
1、创建Controller
@RestController
public class EurekaController {
@GetMapping("/cancel")
public void cancel() {
DiscoveryManager.getInstance().shutdownComponent();
}
}
2、浏览器直接拍http://localhost:2222/cancel即可将客户端实例下线
下线的整体流程图
主要分析绿色的三个步骤
6.1 shutdown()
public class DiscoveryClient implements EurekaClient {
@PreDestroy
@Override
public synchronized void shutdown() {
if (isShutdown.compareAndSet(false, true)) {
......
// 注销监听器
if (statusChangeListener != null && applicationInfoManager != null) {
applicationInfoManager.unregisterStatusChangeListener(statusChangeListener.getId());
}
// 取消定时任务,包括注册、续约、更新注册信息等
cancelScheduledTasks();
// 注销
if (applicationInfoManager != null
&& clientConfig.shouldRegisterWithEureka()
&& clientConfig.shouldUnregisterOnShutdown()) {
applicationInfoManager.setInstanceStatus(InstanceStatus.DOWN);
unregister(); // 向服务端发送下线请求
}
if (eurekaTransport != null) {
// 关闭eurekaTransport
eurekaTransport.shutdown();
}
......
}
}
}
6.2 服务端cancel
public abstract class AbstractInstanceRegistry implements InstanceRegistry {
@Override
public boolean cancel(String appName, String id, boolean isReplication) {
// 1、从内存实例注册表registry删除
// 2、添加到recentCanceledQueue
// 3、从overriddenInstanceStatusMap删除
// 4、添加到recentlyChangedQueue
// 5、从缓存responseCache中删除
return internalCancel(appName, id, isReplication);
}
}
6.3 同步其他server节点
public class PeerAwareInstanceRegistryImpl extends AbstractInstanceRegistry implements PeerAwareInstanceRegistry {
@Override
public boolean cancel(final String appName, final String id,
final boolean isReplication) {
if (super.cancel(appName, id, isReplication)) {
// 除了Action.Cancel与register不同,其他可参考register章节
replicateToPeers(Action.Cancel, appName, id, null, null, isReplication);
return true;
}
return false;
}
}
未完待续