程序员

Spring Cloud Eureka 源码导读

2018-05-09  本文已影响40人  黄大海

设计结构

spring-cloud-common是spring制定的服务注册发现的抽象规范。其具体实现可以适配eureka/consul/zookeeper/etcd.

spring-eureka设计结构 (1).png
服务组册发现框架 CAP支持 协议 说明
eureka AP Simple Peer Replication 简单/Spring集成度高
consul AP Raft 支持跨机房
zookeeper CP Paxos 老牌框架
etcd CP Raft Raft协议比Paxos简单

如何启动

@Import(EnableDiscoveryClientImportSelector.class)
public @interface EnableDiscoveryClient {
    ...
}
public String[] selectImports(AnnotationMetadata metadata) {
    ...
    SpringFactoriesLoader.loadFactoryNames(EnableDiscoveryClient.class)
    ...
}
org.springframework.cloud.client.discovery.EnableDiscoveryClient=\
org.springframework.cloud.netflix.eureka.EurekaDiscoveryClientConfiguration
public class EurekaDiscoveryClientConfiguration {

    class Marker {}

    @Bean
    public Marker eurekaDiscoverClientMarker() {
        return new Marker();
    }
    
    ...
}

@Configuration
...
@ConditionalOnBean(EurekaDiscoveryClientConfiguration.Marker.class)
...
public class EurekaClientAutoConfiguration {
}
@ConditionalOnMissingBean(value = EurekaClient.class, search = SearchStrategy.CURRENT)
public EurekaClient eurekaClient(ApplicationInfoManager manager, EurekaClientConfig config) {
    return new CloudEurekaClient(manager, config, this.optionalArgs, this.context);
}
 private void initScheduledTasks() {
        ...
       if (clientConfig.shouldFetchRegistry()) {
            ...
            scheduler.schedule( new CacheRefreshThread())
            ...
       }
        ...
        if (clientConfig.shouldRegisterWithEureka()) {
            ... 
            // Heartbeat timer
            scheduler.schedule( new HeartbeatThread())
            ...
            // InstanceInfo replicator
            instanceInfoReplicator.start()
        }
       
 }

如何注册

public void start(int initialDelayMs)
    ...
    Future next = scheduler.schedule(this, initialDelayMs, TimeUnit.SECONDS);
    ... 
}
public void run() {
    ...
    discoveryClient.register();
    ...
}
boolean register() throws Throwable {
    EurekaHttpResponse<Void> httpResponse = 
    eurekaTransport.registrationClient.register(instanceInfo);
}
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();
        }
    }
}

如何获取服务列表

private boolean fetchRegistry(boolean forceFullRegistryFetch) {
    ...
    if (...){
        getAndStoreFullRegistry();
    } else {
        getAndUpdateDelta(applications);
    }
   ...
}
private void getAndStoreFullRegistry() throws Throwable {
    ...
    EurekaHttpResponse<Applications> httpResponse = clientConfig.getRegistryRefreshSingleVipAddress() == null
         ? eurekaTransport.queryClient.getApplications(remoteRegionsRef.get())
         : eurekaTransport.queryClient.getVip(clientConfig.getRegistryRefreshSingleVipAddress(), remoteRegionsRef.get());
    localRegionApps.set(this.filterAndShuffle(apps));
    ...
}

Server如何做Replication

@Bean
public PeerAwareInstanceRegistry peerAwareInstanceRegistry(
            ServerCodecs serverCodecs) {
    this.eurekaClient.getApplications(); // force initialization
    return new InstanceRegistry(this.eurekaServerConfig, this.eurekaClientConfig,
        serverCodecs, this.eurekaClient,
        this.instanceRegistryProperties.getExpectedNumberOfRenewsPerMin(),
        this.instanceRegistryProperties.getDefaultOpenForTrafficCount());
}
@Override
public void register(final InstanceInfo info, final boolean isReplication) {
    ...
    super.register(info, leaseDuration, isReplication);
    replicateToPeers(Action.Register, info.getAppName(), info.getId(), info, null, isReplication);
}
private void replicateToPeers(Action action, String appName, String id,
                                  InstanceInfo info /* optional */,
                                  InstanceStatus newStatus /* optional */, boolean isReplication) {
    ...
    // If it is a replication already, do not replicate again as this will create a poison replication
    if (peerEurekaNodes == Collections.EMPTY_LIST || isReplication) {
        return;
    }

    for (final PeerEurekaNode node : peerEurekaNodes.getPeerEurekaNodes()) {
        // If the url represents this host, do not replicate to yourself.
        if (peerEurekaNodes.isThisMyUrl(node.getServiceUrl())) {
            continue;
        }
        replicateInstanceActionsToPeers(action, appName, id, info, newStatus, node);
    }
}
 webResource.header("x-netflix-discovery-replication", "true");
上一篇下一篇

猜你喜欢

热点阅读