<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>${spring.cloud.version}</version> <type>pom</type> <scope>import</scope> </dependency> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId> </dependency> </dependencies>
# Eureka 客户端配置 eureka: client: service-url: defaultZone: http://node2:10002/eureka/,http://node3:10003/eureka/ #本客户端是否注册至eureka register-with-eureka: false #本客户端是否从eureka获取服务列表 fetch-registry: false instance: # 配置经过主机名方式注册 hostname: node1 # 配置实例编号 instance-id: ${eureka.instance.hostname}:${server.port}:@project.version@ # 集群节点之间读取超时时间。单位:毫秒 server: peer-node-read-timeout-ms: 1000 # 服务端口号 server: port: 10001node2配置:
# Eureka 客户端配置 eureka: client: service-url: defaultZone: http://node1:10001/eureka/,http://node3:10003/eureka/ #本客户端是否注册至eureka register-with-eureka: false #本客户端是否从eureka获取服务列表 fetch-registry: false instance: # 配置经过主机名方式注册 hostname: node2 # 配置实例编号 instance-id: ${eureka.instance.hostname}:${server.port}:@project.version@ # 集群节点之间读取超时时间。单位:毫秒 server: peer-node-read-timeout-ms: 1000 # 服务端口号 server: port: 10002node3配置:
# Eureka 客户端配置 eureka: client: service-url: defaultZone: http://node1:10001/eureka/,http://node2:10002/eureka/ #本客户端是否注册至eureka register-with-eureka: false #本客户端是否从eureka获取服务列表 fetch-registry: false instance: # 配置经过主机名方式注册 hostname: node3 # 配置实例编号 instance-id: ${eureka.instance.hostname}:${server.port}:@project.version@ # 集群节点之间读取超时时间。单位:毫秒 server: peer-node-read-timeout-ms: 1000 # 服务端口号 server: port: 10003
@EnableEurekaServer @SpringBootApplication public class EurekaServiceApplication { public static void main(String[] args) { SpringApplication.run(EurekaServiceApplication.class, args); } }补充说明:每个eureak服务,须要指定出其余的服务节点名字,组成集群组,通过以上配置咱们分别启动三个服务的main函数,就能够把这组有三个节点node一、node二、node3组成的集群启动起来,对外提供注册服务
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency>2.二、注册中心配置
spring: application: name: orderService server: port: 8761 eureka: instance: hostname: myapp client: registerWithEureka: true fetchRegistry: true serviceUrl: defaultZone: http://node2:10002/eureka/,http://node3:10003/eureka/,http://node1:10001/eureka/2.三、启动服务注册
//@EnableDiscoveryClient //@EnableEurekaClient @SpringBootApplication public class OrderApplication { /** * @MethodName: main * @Description: TODO(这里用一句话描述这个方法的做用) * @param @param args * @return void * @throws */ public static void main(String[] args) { //DiscoveryClient tt = null; SpringApplication.run(OrderApplication.class, args); } }
补充下,咱们在配置文件中指定了,该客户端须要向server端进行注册,并从server端获取服务列表,因此运行的main函数中,能够不须要作@EnableEurekaClient或@EnableDiscoveryClient的注解!java
@Bean(destroyMethod = "shutdown") @ConditionalOnMissingBean(value = EurekaClient.class, search = SearchStrategy.CURRENT) @org.springframework.cloud.context.config.annotation.RefreshScope @Lazy public EurekaClient eurekaClient(ApplicationInfoManager manager, EurekaClientConfig config, EurekaInstanceConfig instance) { manager.getInfo(); // force initialization return new CloudEurekaClient(manager, config, this.optionalArgs, this.context); }
二、CloudEurekaClient继承自DiscoveryClient,在DiscoveryClient完成核心的注册流程,以下node
@Inject DiscoveryClient(ApplicationInfoManager applicationInfoManager, EurekaClientConfig config, AbstractDiscoveryClientOptionalArgs args, Provider<BackupRegistry> backupRegistryProvider) { if (args != null) { this.healthCheckHandlerProvider = args.healthCheckHandlerProvider; this.healthCheckCallbackProvider = args.healthCheckCallbackProvider; this.eventListeners.addAll(args.getEventListeners()); this.preRegistrationHandler = args.preRegistrationHandler; } else { this.healthCheckCallbackProvider = null; this.healthCheckHandlerProvider = null; this.preRegistrationHandler = null; } this.applicationInfoManager = applicationInfoManager; InstanceInfo myInfo = applicationInfoManager.getInfo(); clientConfig = config; staticClientConfig = clientConfig; transportConfig = config.getTransportConfig(); instanceInfo = myInfo; if (myInfo != null) { appPathIdentifier = instanceInfo.getAppName() + "/" + instanceInfo.getId(); } else { logger.warn("Setting instanceInfo to a passed in null value"); } this.backupRegistryProvider = backupRegistryProvider; this.urlRandomizer = new EndpointUtils.InstanceInfoBasedUrlRandomizer(instanceInfo); localRegionApps.set(new Applications()); fetchRegistryGeneration = new AtomicLong(0); remoteRegionsToFetch = new AtomicReference<String>(clientConfig.fetchRegistryForRemoteRegions()); remoteRegionsRef = new AtomicReference<>(remoteRegionsToFetch.get() == null ? null : remoteRegionsToFetch.get().split(",")); if (config.shouldFetchRegistry()) { //若是开启了从eureka获取服务列表,建立列表更新的,健康监控 this.registryStalenessMonitor = new ThresholdLevelsMetric(this, METRIC_REGISTRY_PREFIX + "lastUpdateSec_", new long[]{15L, 30L, 60L, 120L, 240L, 480L}); } else { this.registryStalenessMonitor = ThresholdLevelsMetric.NO_OP_METRIC; } if (config.shouldRegisterWithEureka()) { //若是开启了注册功能,建立一个eureka之间心跳监控 this.heartbeatStalenessMonitor = new ThresholdLevelsMetric(this, METRIC_REGISTRATION_PREFIX + "lastHeartbeatSec_", new long[]{15L, 30L, 60L, 120L, 240L, 480L}); } else { this.heartbeatStalenessMonitor = ThresholdLevelsMetric.NO_OP_METRIC; } logger.info("Initializing Eureka in region {}", clientConfig.getRegion()); //没有开启获取注册列表和服务注册功能,直接返回 if (!config.shouldRegisterWithEureka() && !config.shouldFetchRegistry()) { logger.info("Client configured to neither register nor query for data."); scheduler = null; heartbeatExecutor = null; cacheRefreshExecutor = null; eurekaTransport = null; instanceRegionChecker = new InstanceRegionChecker(new PropertyBasedAzToRegionMapper(config), clientConfig.getRegion()); // This is a bit of hack to allow for existing code using DiscoveryManager.getInstance() // to work with DI'd DiscoveryClient DiscoveryManager.getInstance().setDiscoveryClient(this); DiscoveryManager.getInstance().setEurekaClientConfig(config); initTimestampMs = System.currentTimeMillis(); logger.info("Discovery Client initialized at timestamp {} with initial instances count: {}", initTimestampMs, this.getApplications().size()); return; // no need to setup up an network tasks and we are done } //下面是开启了服务注册和列表查询 try { // default size of 2 - 1 each for heartbeat and cacheRefresh //这是一个定时任务,分配了两个调度任务,一个是给心跳维持的线程池,一个是给服务列表刷新的线程池 scheduler = Executors.newScheduledThreadPool(2, new ThreadFactoryBuilder() .setNameFormat("DiscoveryClient-%d") .setDaemon(true) .build()); //心跳维持线程池,经过线程池方式实现了隔离 heartbeatExecutor = new ThreadPoolExecutor( 1, clientConfig.getHeartbeatExecutorThreadPoolSize(), 0, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(), new ThreadFactoryBuilder() .setNameFormat("DiscoveryClient-HeartbeatExecutor-%d") .setDaemon(true) .build() ); // use direct handoff //列表刷新的线程池,经过线程池刷新了隔离 cacheRefreshExecutor = new ThreadPoolExecutor( 1, clientConfig.getCacheRefreshExecutorThreadPoolSize(), 0, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(), new ThreadFactoryBuilder() .setNameFormat("DiscoveryClient-CacheRefreshExecutor-%d") .setDaemon(true) .build() ); // use direct handoff eurekaTransport = new EurekaTransport(); scheduleServerEndpointTask(eurekaTransport, args); AzToRegionMapper azToRegionMapper; if (clientConfig.shouldUseDnsForFetchingServiceUrls()) { azToRegionMapper = new DNSBasedAzToRegionMapper(clientConfig); } else { azToRegionMapper = new PropertyBasedAzToRegionMapper(clientConfig); } if (null != remoteRegionsToFetch.get()) { azToRegionMapper.setRegionsToFetch(remoteRegionsToFetch.get().split(",")); } instanceRegionChecker = new InstanceRegionChecker(azToRegionMapper, clientConfig.getRegion()); } catch (Throwable e) { throw new RuntimeException("Failed to initialize DiscoveryClient!", e); } if (clientConfig.shouldFetchRegistry() && !fetchRegistry(false)) { fetchRegistryFromBackup(); } // call and execute the pre registration handler before all background tasks (inc registration) is started if (this.preRegistrationHandler != null) { this.preRegistrationHandler.beforeRegistration(); } if (clientConfig.shouldRegisterWithEureka() && clientConfig.shouldEnforceRegistrationAtInit()) { try {//这里完成启动的时候注册,调用远程的eureka server,如:http://node1:10001/eureka/apps/,经过jersey实现rest调用,详细的注册代码,见下方 if (!register() ) { throw new IllegalStateException("Registration error at startup. Invalid server response."); } } catch (Throwable th) { logger.error("Registration error at startup: {}", th.getMessage()); throw new IllegalStateException(th); } } // finally, init the schedule tasks (e.g. cluster resolvers, heartbeat, instanceInfo replicator, fetch //完成调度任务的初始化,具体就是本地服务列表刷新任务、心跳监测任务的初始化 initScheduledTasks(); try { Monitors.registerObject(this); } catch (Throwable e) { logger.warn("Cannot register timers", e); } // This is a bit of hack to allow for existing code using DiscoveryManager.getInstance() // to work with DI'd DiscoveryClient DiscoveryManager.getInstance().setDiscoveryClient(this); DiscoveryManager.getInstance().setEurekaClientConfig(config); initTimestampMs = System.currentTimeMillis(); logger.info("Discovery Client initialized at timestamp {} with initial instances count: {}", initTimestampMs, this.getApplications().size()); }
三、注册的具体动做:参见AbstractJerseyEurekaHttpClient类的register方法,其实就是发送的一个http请求,以下:spring
public EurekaHttpResponse<Void> register(InstanceInfo info) { String urlPath = "apps/" + info.getAppName(); ClientResponse response = null; try { 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); return anEurekaHttpResponse(response.getStatus()).headers(headersOf(response)).build(); } finally { if (logger.isDebugEnabled()) { logger.debug("Jersey HTTP POST {}/{} with instance {}; statusCode={}", serviceUrl, urlPath, info.getId(), response == null ? "N/A" : response.getStatus()); } if (response != null) { response.close(); } } }
四、心跳维持和缓存刷新,这一步就是在initScheduleTasks完成的
心跳维持的线程池,首次注册完成以后,如何保证这个注册的’有效性‘,因此须要经过心跳维持的线程(HeartbeatThread)作续租,整个过程就是经过前面提到的定时任务,定时去和eureka server进行通讯,告诉它服务还在,服务是有效的!具体的’续租‘逻辑以下:缓存
boolean renew() { EurekaHttpResponse<InstanceInfo> httpResponse; try { httpResponse = eurekaTransport.registrationClient.sendHeartBeat(instanceInfo.getAppName(), instanceInfo.getId(), instanceInfo, null); logger.debug(PREFIX + "{} - Heartbeat status: {}", appPathIdentifier, httpResponse.getStatusCode()); if (httpResponse.getStatusCode() == 404) { REREGISTER_COUNTER.increment(); logger.info(PREFIX + "{} - Re-registering apps/{}", appPathIdentifier, instanceInfo.getAppName()); long timestamp = instanceInfo.setIsDirtyWithTime(); boolean success = register(); if (success) { instanceInfo.unsetIsDirty(timestamp); } return success; } return httpResponse.getStatusCode() == 200; } catch (Throwable e) { logger.error(PREFIX + "{} - was unable to send heartbeat!", appPathIdentifier, e); return false; } }
上面提到了服务列表刷新线程,如何保证,本地的服务列表是有效的:即以下场景
4.一、A服务首次启动,注册至eureka的server
4.二、eureka client经过CacheRefreshThread获取服务列表
4.三、A服务宕机,未能及时经过HeartbeatThread向server作’续租‘
4.四、CacheRefreshThread获取最新的服务列表,最新的服务列表不包含A服务
CacheRefreshThread实现服务列表刷新逻辑以下:app
private boolean fetchRegistry(boolean forceFullRegistryFetch) { Stopwatch tracer = FETCH_REGISTRY_TIMER.start(); try { // If the delta is disabled or if it is the first time, get all // applications Applications applications = getApplications(); if (clientConfig.shouldDisableDelta() || (!Strings.isNullOrEmpty(clientConfig.getRegistryRefreshSingleVipAddress())) || forceFullRegistryFetch || (applications == null) || (applications.getRegisteredApplications().size() == 0) || (applications.getVersion() == -1)) //Client application does not have latest library supporting delta { logger.info("Disable delta property : {}", clientConfig.shouldDisableDelta()); logger.info("Single vip registry refresh property : {}", clientConfig.getRegistryRefreshSingleVipAddress()); logger.info("Force full registry fetch : {}", forceFullRegistryFetch); logger.info("Application is null : {}", (applications == null)); logger.info("Registered Applications size is zero : {}", (applications.getRegisteredApplications().size() == 0)); logger.info("Application version is -1: {}", (applications.getVersion() == -1)); getAndStoreFullRegistry(); } else { getAndUpdateDelta(applications); } applications.setAppsHashCode(applications.getReconcileHashCode()); logTotalInstances(); } catch (Throwable e) { logger.error(PREFIX + "{} - was unable to refresh its cache! status = {}", appPathIdentifier, e.getMessage(), e); return false; } finally { if (tracer != null) { tracer.stop(); } } // Notify about cache refresh before updating the instance remote status onCacheRefreshed(); // Update remote status based on refreshed data held in the cache updateInstanceRemoteStatus(); // registry was fetched successfully, so return true return true; }