Eureka源码分析
- Eureka server
入口:
Spring.factories
PS:
意味着如果加载EurekaServerAutoConfiguration成功,需要
@ConditionalOnBean(EurekaServerMarkerConfiguration.Marker.class)需加载成功.
通过@Bean注入了很多类
本质上, eureka-server包含很多事件:
EurekaInstanceCanceledEvent | 服务下线事件 |
EurekaInstanceRegisteredEvent | 服务注册事件 |
EurekaInstanceRenewedEvent | 服务续约事件 |
EurekaRegistryAvailableEvent | Eureka注册中心启动事件 |
EurekaServerStartedEvent | Eureka server启动事件 |
Java扩展: EventObject->EventListener
包含注册\下线\续约等
事件注册之前, 需要有监听器, eureka所用的监听器是EurekaEventListener
针对上面五个事件, 我们可以自定义监听器
package com.macro.cloud;
import com.netflix.appinfo.InstanceInfo;
import org.springframework.cloud.netflix.eureka.server.event.*;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
@Component
public class EurekaStateChangeListener {
@EventListener
public void listen(EurekaInstanceCanceledEvent eurekaInstanceCanceledEvent) {
//服务断线事件
String appName = eurekaInstanceCanceledEvent.getAppName();
String serverId = eurekaInstanceCanceledEvent.getServerId();
System.out.println(appName);
System.out.println(serverId);
System.out.println("EurekaInstanceCanceledEvent");
}
@EventListener
public void listen(EurekaInstanceRegisteredEvent event) {
InstanceInfo instanceInfo = event.getInstanceInfo();
System.out.println(instanceInfo);
System.out.println("EurekaInstanceRegisteredEvent");
}
@EventListener
public void listen(EurekaInstanceRenewedEvent event) {
event.getAppName();
event.getServerId();
System.out.println("EurekaInstanceRenewedEvent");
}
@EventListener
public void listen(EurekaRegistryAvailableEvent event) {
System.out.println("EurekaRegistryAvailableEvent");
}
@EventListener
public void listen(EurekaServerStartedEvent event) {
System.out.println("EurekaServerStartedEvent");
//Server启动
}
}
其中eureka-server启动时候, 会出发最后两个事件, 即:
EurekaRegistryAvailableEvent 和 EurekaServerStartedEvent.
当eureka-client启动后, 会出发EurekaInstanceRegisteredEvent事件.
Eurekaserver总结如下:
- Eureka client
ApplicationListenerMethodAdapter.java
Eureka-client 底层是要了jerseyClient
Builder resourceBuilder = jerseyClient.resource(serviceUrl).path(urlPath).getRequestBuilder();
addExtraHeaders(resourceBuilder);
response = resourceBuilder
.header("Accept-Encoding", "gzip")
.type(MediaType.APPLICATION_JSON_TYPE)
.accept(MediaType.APPLICATION_JSON)
.post(ClientResponse.class, info);
欢迎关注公众号: 戏说码农职场