eureka源码之eureka-client服务注册/心跳机制

 

 

入口

 

 

public class EurekaClientAutoConfiguration {

....省略……
// 获取当前微服务的相关的配置信息
@Bean
	@ConditionalOnMissingBean(value = EurekaInstanceConfig.class, search = SearchStrategy.CURRENT)
	public EurekaInstanceConfigBean eurekaInstanceConfigBean(InetUtils inetUtils,
															 ManagementMetadataProvider managementMetadataProvider) {
		String hostname = getProperty("eureka.instance.hostname");
		boolean preferIpAddress = Boolean.parseBoolean(getProperty("eureka.instance.prefer-ip-address"));
		String ipAddress = getProperty("eureka.instance.ip-address");
		boolean isSecurePortEnabled = Boolean.parseBoolean(getProperty("eureka.instance.secure-port-enabled"));

		String serverContextPath = env.getProperty("server.context-path", "/");
		int serverPort = Integer.valueOf(env.getProperty("server.port", env.getProperty("port", "8080")));

		Integer managementPort = env.getProperty("management.server.port", Integer.class);// nullable. should be wrapped into optional
		String managementContextPath = env.getProperty("management.server.context-path");// nullable. should be wrapped into optional
		Integer jmxPort = env.getProperty("com.sun.management.jmxremote.port", Integer.class);//nullable
		EurekaInstanceConfigBean instance = new EurekaInstanceConfigBean(inetUtils);

		instance.setNonSecurePort(serverPort);
		instance.setInstanceId(getDefaultInstanceId(env));
		instance.setPreferIpAddress(preferIpAddress);
		instance.setSecurePortEnabled(isSecurePortEnabled);
		if (StringUtils.hasText(ipAddress)) {
			instance.setIpAddress(ipAddress);
		}

		if(isSecurePortEnabled) {
			instance.setSecurePort(serverPort);
		}

		if (StringUtils.hasText(hostname)) {
			instance.setHostname(hostname);
		}
		String statusPageUrlPath = getProperty("eureka.instance.status-page-url-path");
		String healthCheckUrlPath = getProperty("eureka.instance.health-check-url-path");

		if (StringUtils.hasText(statusPageUrlPath)) {
			instance.setStatusPageUrlPath(statusPageUrlPath);
		}
		if (StringUtils.hasText(healthCheckUrlPath)) {
			instance.setHealthCheckUrlPath(healthCheckUrlPath);
		}

		ManagementMetadata metadata = managementMetadataProvider.get(instance, serverPort,
				serverContextPath, managementContextPath, managementPort);

		if(metadata != null) {
			instance.setStatusPageUrl(metadata.getStatusPageUrl());
			instance.setHealthCheckUrl(metadata.getHealthCheckUrl());
			if(instance.isSecurePortEnabled()) {
				instance.setSecureHealthCheckUrl(metadata.getSecureHealthCheckUrl());
			}
			Map<String, String> metadataMap = instance.getMetadataMap();
			if (metadataMap.get("management.port") == null) {
				metadataMap.put("management.port", String.valueOf(metadata.getManagementPort()));
			}
		}

		setupJmxPort(instance, jmxPort);
		return instance;
	}

…… 省略……


	@Configuration
	@ConditionalOnMissingRefreshScope
	protected static class EurekaClientConfiguration {

		…… 省略……

		@Bean(destroyMethod = "shutdown")
		@ConditionalOnMissingBean(value = EurekaClient.class, search = SearchStrategy.CURRENT)
		public EurekaClient eurekaClient(ApplicationInfoManager manager, EurekaClientConfig config) {
			return new CloudEurekaClient(manager, config, this.optionalArgs,
					this.context);
		}

    …… 省略……
}

_________________________________________________________________________________________


public class CloudEurekaClient extends DiscoveryClient {
 …… 省略……
	public CloudEurekaClient( …… 省略……) {
		super(applicationInfoManager, config, args);
		 …… 省略……
	}
 …… 省略……
}

CloudEurekaClient#CloudEurekaClient(省略) {
		super(applicationInfoManager, config, args);
		//省略
	}
_________________________________________________________________________________________


DiscoveryClient# DiscoveryClient(省略) {
        this(applicationInfoManager, config, args, new Provider<BackupRegistry>() {
            private volatile BackupRegistry backupRegistryInstance;
            //这个get是拿备用服务,eureka-client不仅仅可以配置集群服务,还可以配置一些备用的服务,
            //如果集群服务拿不到会去备用服务拿
            @Override
            public synchronized BackupRegistry get() {
            	//省略
            }
        }, randomizer);
    }
_________________________________________________________________________________________


DiscoveryClient最终的构造器,在DiscoveryClient代码320行
DiscoveryClient# DiscoveryClient(){
	//如果客户端配置了 既不要注册到服务中心,也不要从服务中心拿数据,那么本eureka-client其实就失去了意义,直接return
	if (!config.shouldRegisterWithEureka() && !config.shouldFetchRegistry()) {
            //省略 把很多值置为null
            //直接return
            return;  
   }
	//下面是几行伪代码
	//核心池大小为2的线程池
	ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(2);
	//心跳机制执行,其实就是定时发送心跳请求给eureka-server告诉它我还活着,不要把我剔除
	ThreadPoolExecutor heartbeatExecutor = new ThreadPoolExecutor();
	//服务发现机制执行,其实就是定时去eureka-server拿微服务实例数据
    ThreadPoolExecutor cacheRefreshExecutor = new ThreadPoolExecutor();
    
    //如果客户端配置应该从注册中心拿数据,并且这次fetchRegistry(即服务发现)失败了,则会从备用服务拿
 	if (clientConfig.shouldFetchRegistry() && !fetchRegistry(false)) {
            fetchRegistryFromBackup();
    }
	//如果配置了应该注册到注册中心(默认true)&&初始化的时候强制注册(默认false),所以不做配置的情况下,不会进if
	//但没关系,心跳的时候会注册的,这个看到后面就懂了
    if (clientConfig.shouldRegisterWithEureka() && clientConfig.shouldEnforceRegistrationAtInit()) {
       		if (!register()) {
                 throw new IllegalStateException("");
           }              
    }
    
    initScheduledTasks();
                   
}

上面这些代码就是eureka-client初始化的代码,到此为止在默认配置的情况下只进行了一次服务发现,还没有进行服务注册

服务注册+心跳机制

private void initScheduledTasks() {
    ……省略……
        //省略cacheRefreshTask ,因为这个是服务发现的任务,下篇博客说
		//应该注册到注册中心
        if (clientConfig.shouldRegisterWithEureka()) {
        	//心跳的间隔(单位s)
            int renewalIntervalInSecs = instanceInfo.getLeaseInfo().getRenewalIntervalInSecs();
            int expBackOffBound = clientConfig.getHeartbeatExecutorExponentialBackOffBound();
            //心跳任务
            heartbeatTask = new TimedSupervisorTask(
                    "heartbeat",
                    scheduler,
                    heartbeatExecutor,
                    renewalIntervalInSecs,
                    TimeUnit.SECONDS,
                    expBackOffBound,
                    new HeartbeatThread()
            );
            //默认30s执行一次心跳
            scheduler.schedule(heartbeatTask,renewalIntervalInSecs, TimeUnit.SECONDS);
    ……省略……
}

HeartbeatThread心跳检测

 private class HeartbeatThread implements Runnable {
        public void run() {
            if (renew()) {
                lastSuccessfulHeartbeatTimestamp = System.currentTimeMillis();
            }
        }
    }


 

boolean renew() {
		//这里就是访问eureka-server的renew续期接口了,在之前的博文说过,不再赘述
 		 EurekaHttpResponse<InstanceInfo>  httpResponse = 
 		 eurekaTransport.registrationClient.sendHeartBeat
 		 (instanceInfo.getAppName(), instanceInfo.getId(), instanceInfo, null);
          //如果续期失败(失败原因:没有找到要续期的微服务,该微服务已过期)
            if (httpResponse.getStatusCode() == Status.NOT_FOUND.getStatusCode()) {
              	//续期失败就转为注册
                boolean success = register();
                return success;
            }
            return httpResponse.getStatusCode() == Status.OK.getStatusCode();
        
    }

心跳检测请求地址:http://localhost:3000/eureka/apps/CLIENT-POWER/power-5001

eureka-service端对应的地址

@Path("/{version}/apps")
@Produces({"application/xml", "application/json"})
public class ApplicationsResource {
 
// 心跳检测
    @Path("{appId}")
    public ApplicationResource getApplicationResource(
            @PathParam("version") String version,
            @PathParam("appId") String appId) {
        CurrentRequestVersion.set(Version.toEnum(version));
        return new ApplicationResource(appId, serverConfig, registry);
    }

}

 

 

 

总结

1、@EnableEurekaClient此注解可加可不加,有点鸡肋这个
2:eureka-client初始化过程中会先服务发现,如果失败会去备用服务拿
3:可以配置EnforceRegistrationAtInit属性强制初始化的时候就进行服务注册
4:初始化过程开启定时器30s执行一次心跳续约,如果心跳续约失败会进行服务注册
 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章