Eureka 1.3.5

参考文档

eureka-client
https://cloud.spring.io/spring-cloud-static/Dalston.SR5/multi/multi__service_discovery_eureka_clients.html
eureka-service
https://cloud.spring.io/spring-cloud-static/Dalston.SR5/multi/multi_spring-cloud-eureka-server.html#netflix-eureka-server-starter
springboot-actuator
https://docs.spring.io/spring-boot/docs/1.3.5.RELEASE/reference/html/production-ready.html
eureka wiki
https://github.com/Netflix/eureka/wiki

1.使用EurekaClient

1.1引入pom

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>

1.2配置@EnableEurekaClient

@EnableEurekaClient
@SpringBootApplication
public class Application {

}

1.3配置yml文件

eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/
  instance:
    hostname: peer1
    appname: ${spring.application.name}
    virtual-host-name: ${spring.application.name}
    non-secure-port: ${server.port}

1.3.1 appname、virtual-host-name、non-secure-port
The default application name (service ID), virtual host and non-secure port,
taken from the Environment, are ${spring.application.name}, ${spring.application.name} and ${server.port} respectively.

1.3.2必须配置spring.application.name
@EnableEurekaClient makes the app into both a Eureka “instance” (i.e. it registers itself)
and a “client” (i.e. it can query the registry to locate other services).
The instance behaviour is driven by eureka.instance.* configuration keys,
but the defaults will be fine if you ensure that your application has a spring.application.name (this is the default for the Eureka service ID, or VIP).

1.3.3配置文件bean
See EurekaInstanceConfigBean and EurekaClientConfigBean for more details of the configurable options.EurekaServerConfigBean
https://github.com/spring-cloud/spring-cloud-netflix/blob/1.3.x/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/EurekaInstanceConfigBean.java

https://github.com/spring-cloud/spring-cloud-netflix/blob/1.3.x/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/EurekaClientConfigBean.java

https://github.com/spring-cloud/spring-cloud-netflix/blob/1.3.x/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/EurekaServerConfigBean.java

2 配置Eureka Service

2.1引入依赖包

<dependency>
    <groupId>org.springframework.cloud</groupId>
   <artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>

2.2配置app

@SpringBootApplication
@EnableEurekaServer
public class Application {

    public static void main(String[] args) {
        new SpringApplicationBuilder(Application.class).web(true).run(args);
    }

}

2.3 hostname

eureka:
  instance:
    hostname

/**
 * Flag to say that, when guessing a hostname, the IP address of the server should be
 * used in prference to the hostname reported by the OS.
 */
private boolean preferIpAddress = false; 

/**
 * The hostname if it can be determined at configuration time (otherwise it will be
 * guessed from OS primitives).
 */
private String hostname; 

/**
 * Get the IPAdress of the instance. This information is for academic purposes only as
 * the communication from other instances primarily happen using the information
 * supplied in {@link #getHostName(boolean)}.
 */
private String ipAddress; 

public String getHostname() {
    return getHostName(false);
} 

@Override
public String getHostName(boolean refresh) {
    if (refresh && !this.hostInfo.override) {
        this.ipAddress = this.hostInfo.getIpAddress();
        this.hostname = this.hostInfo.getHostname();
    }
    return this.preferIpAddress ? this.ipAddress : this.hostname;
}

2.2registerWithEureka

eureka:
  client:
    registerWithEureka: false 
/**
 * Indicates whether or not this instance should register its information with eureka
 * server for discovery by others.
 *
 * In some cases, you do not want your instances to be discovered whereas you just
 * want do discover other instances.
 */
private boolean registerWithEureka = true;

2.3fetchRegistry

eureka:
  client:
    fetchRegistry: false
    
/**
 * Indicates whether this client should fetch eureka registry information from eureka
 * server.
 */
private boolean fetchRegistry = true;

2.4healthcheck

eureka:
  client:
    healthcheck:
      enabled: true

By default, Eureka uses the client heartbeat to determine if a client is up.
Unless specified otherwise the Discovery Client will not propagate the current health check status of the application per the Spring Boot Actuator.
Which means that after successful registration Eureka will always announce that the application is in ‘UP’ state.
This behaviour can be altered by enabling Eureka health checks, which results in propagating application status to Eureka.
As a consequence every other application won’t be sending traffic to application in state other then ‘UP’.

添加以下依赖包可以将应用自身的状态注册到eureka

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

2.4.2Endpoints
Endpoints
Actuator endpoints allow you to monitor and interact with your application.
Spring Boot includes a number of built-in endpoints and you can also add your own.
For example the health endpoint provides basic application health information.
The way that endpoints are exposed will depend on the type of technology that you choose.
Most applications choose HTTP monitoring, where the ID of the endpoint is mapped to a URL.
For example, by default, the health endpoint will be mapped to /health.

endpoint描述Sensitive Default
actuatorProvides a hypermedia-based “discovery page” for the other endpoints. Requires Spring HATEOAS to be on the classpath.true
autoconfigDisplays an auto-configuration report showing all auto-configuration candidates and the reason why they ‘were’ or ‘were not’ applied.true
beansDisplays a complete list of all the Spring beans in your application.true
configpropsDisplays a collated list of all @ConfigurationProperties.true
docsDisplays documentation, including example requests and responses, for the Actuator’s endpoints. Requires spring-boot-actuator-docs to be on the classpath.false
dumpPerforms a thread dump.true
envExposes properties from Spring’s ConfigurableEnvironment. true
flywayShows any Flyway database migrations that have been applied.true
healthShows application health information (when the application is secure, a simple ‘status’ when accessed over an unauthenticated connection or full message details when authenticated). false
infoDisplays arbitrary application info.false
liquibaseShows any Liquibase database migrations that have been applied.true
logfileReturns the contents of the logfile (if logging.file or logging.path properties have been set). Only available via MVC. Supports the use of the HTTP Range header to retrieve part of the log file’s content.true
metricsShows ‘metrics’ information for the current application.true
mappingsDisplays a collated list of all @RequestMapping paths.true
shutdownAllows the application to be gracefully shutdown (not enabled by default).true
traceDisplays trace information (by default the last few HTTP requests).true

Depending on how an endpoint is exposed, the sensitive property may be used as a security hint. For example, sensitive endpoints will require a username/password when they are accessed over HTTP (or simply disabled if web security is not enabled).
2.4.3 配置endpoint
Endpoints can be customized using Spring properties. You can change if an endpoint is enabled, if it is considered sensitive and even its id.

endpoints.beans.id=springbeans
endpoints.beans.sensitive=false
endpoints.shutdown.enabled=true

By default, all endpoints except for shutdown are enabled. If you prefer to specifically “opt-in” endpoint enablement you can use the endpoints.enabled property. For example, the following will disable all endpoints except for info:

endpoints.enabled=false
endpoints.info.enabled=true

Likewise, you can also choose to globally set the “sensitive” flag of all endpoints. By default, the sensitive flag depends on the type of endpoint (see the table above). For example, to mark all endpoints as sensitive except info:

endpoints.sensitive=true
endpoints.info.sensitive=false

2.4.4使actuator endpoint 起作用

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-hateoas</artifactId>
</dependency>

2.4.5 跨域支持

endpoints.cors.allowed-origins=http://example.com
endpoints.cors.allowed-methods=GET,POST

2.4.6 health Endpoint
Health information can be used to check the status of your running application. It is often used by monitoring software to alert someone if a production system goes down. The default information exposed by the health endpoint depends on how it is accessed. For an unauthenticated connection in a secure application a simple ‘status’ message is returned, and for an authenticated connection additional details are also displayed (see Section 46.6, “HTTP health endpoint access restrictions” for HTTP details).
Health information is collected from all HealthIndicator beans defined in your ApplicationContext. Spring Boot includes a number of auto-configured HealthIndicators and you can also write your own.
Information returned by HealthIndicators is often somewhat sensitive in nature. For example, you probably don’t want to publish details of your database server to the world. For this reason, by default, only the health status is exposed over an unauthenticated HTTP connection. If you are happy for complete health information to always be exposed you can set endpoints.health.sensitive to false.

endpoints.health.sensitive to false

Health responses are also cached to prevent “denial of service” attacks. Use the endpoints.health.time-to-live property if you want to change the default cache period of 1000 milliseconds.

endpoints.health.time-to-live

2.4.7 系统自带的健康指标

NameDescription
CassandraHealthIndicatorChecks that a Cassandra database is up.
DiskSpaceHealthIndicatorChecks for low disk space.
DataSourceHealthIndicatorChecks that a connection to DataSource can be obtained.
ElasticsearchHealthIndicatorChecks that an ElasticSearch cluster is up.
JmsHealthIndicatorChecks that a JMS broker is up.
MailHealthIndicatorChecks that a mail server is up.
MongoHealthIndicatorChecks that a Mongo database is up.
RabbitHealthIndicatorChecks that a Rabbit server is up.
RedisHealthIndicatorChecks that a Redis server is up.
SolrHealthIndicatorChecks that a Solr server is up.

2.4.6自定义健康指标MyHealthIndicator

import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.stereotype.Component;

@Component
public class MyHealthIndicator implements HealthIndicator {

    @Override
    public Health health() {
        int errorCode = check(); // perform some specific health check
        if (errorCode != 0) {
            return Health.down().withDetail("Error Code", errorCode).build();
        }
        return Health.up().build();
    }

}

The identifier for a given HealthIndicator is the name of the bean without the HealthIndicator suffix if it exists. In the example above, the health information will be available in an entry named my.

2.5 serviceUrl

eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:${server.port}/eureka/
      
/**
 * Map of availability zone to list of fully qualified URLs to communicate with eureka
 * server. Each value can be a single URL or a comma separated list of alternative
 * locations.
 *
 * Typically the eureka server URLs carry protocol,host,port,context and version
 * information if any. Example:
 * https://ec2-256-156-243-129.compute-1.amazonaws.com:7001/eureka/
 *
 * The changes are effective at runtime at the next service url refresh cycle as
 * specified by eurekaServiceUrlPollIntervalSeconds.
 */
private Map<String, String> serviceUrl = new HashMap<>();

	{
		this.serviceUrl.put(DEFAULT_ZONE, DEFAULT_URL);
	}

2.6 enableSelfPreservation

eureka:      
  server:
    enableSelfPreservation: false
    
private boolean enableSelfPreservation = true;
@Override
public boolean shouldEnableSelfPreservation() {
    return this.enableSelfPreservation;
}

https://github.com/Netflix/eureka/wiki/Server-Self-Preservation-Mode

2.7 eviction-interval-timer-in-ms

eureka:
  server:
    #服务端调用evict频率,如果此值设置过大,会导致服务停止后不能及时被发现,默认60s
    eviction-interval-timer-in-ms: 1000
private long evictionIntervalTimerInMs = 60 * 1000;

https://blog.csdn.net/lc0817/article/details/54375802

2.8 useReadOnlyResponseCache

eureka: 
  server:
     # 设置read Write CacheMap的expire After Write参数,指定写入多长时间后过期
     # 有效防止的问题是:应用实例下线时有告知Eureka server下线,但是由于Eureka server的REST API有response cache,因此需要等待缓存过期才能更新
    # response-cache-auto-expiration-in-seconds: 5
    use-read-only-response-cache: true
    useReadOnlyResponseCache
private boolean useReadOnlyResponseCache = true;

2.9 response-cache-update-interval-ms

eureka:
  server:
      # 有效防止的问题是:应用实例下线时有告知Eureka server下线,但是由于Eureka server的REST API有response cache,因此需要等待缓存过期才能更新
    response-cache-update-interval-ms: 2000
private long responseCacheUpdateIntervalMs = 30 * 1000;

com.netflix.eureka.registry.ResponseCacheImpl

 private final ConcurrentMap<Key, Value> readOnlyCacheMap = new ConcurrentHashMap<Key, Value>();

    private final LoadingCache<Key, Value> readWriteCacheMap;
 ResponseCacheImpl(EurekaServerConfig serverConfig, ServerCodecs serverCodecs, AbstractInstanceRegistry registry) {   
    if (shouldUseReadOnlyResponseCache) {
            timer.schedule(getCacheUpdateTask(),
                    new Date(((System.currentTimeMillis() / responseCacheUpdateIntervalMs) * responseCacheUpdateIntervalMs)
                            + responseCacheUpdateIntervalMs),
                    responseCacheUpdateIntervalMs);
        }
 }
 
  private TimerTask getCacheUpdateTask() {
        return new TimerTask() {
            @Override
            public void run() {
                logger.debug("Updating the client cache from response cache");
                for (Key key : readOnlyCacheMap.keySet()) {
                    if (logger.isDebugEnabled()) {
                        Object[] args = {key.getEntityType(), key.getName(), key.getVersion(), key.getType()};
                        logger.debug("Updating the client cache from response cache for key : {} {} {} {}", args);
                    }
                    try {
                        CurrentRequestVersion.set(key.getVersion());
                        Value cacheValue = readWriteCacheMap.get(key);
                        Value currentCacheValue = readOnlyCacheMap.get(key);
                        if (cacheValue != currentCacheValue) {
                            readOnlyCacheMap.put(key, cacheValue);
                        }
                    } catch (Throwable th) {
                        logger.error("Error while updating the client cache from response cache", th);
                    }
                }
            }
        };
    }

2.10 datacenter

datacenter
https://github.com/Netflix/eureka/wiki/Configuring-Eureka

2.11 environment

environment
https://github.com/Netflix/eureka/wiki/Configuring-Eureka
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值