Spring Cloud Eureka整合使用和配置

遵循SpringBoot三板斧

服務端

第一步加依賴

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

第二步加註解

//在啓動類上加註解
@EnableEurekaServer
@SpringBootApplication
public class EurekaApplication {
    public static void main(String[] args) {
        SpringApplication.run(EurekaApplication.class, args);
    }
}

第三步寫配置

spring:
  application:
    name: eureka
# 詳見EurekaServerConfigBean,需要注意與Client和Instance在client的jar包不同,Server是在server的jar包。
# eureka的各項配置可見EurekaXXXConfigBean。
eureka:
  datacenter: cloud           # 修改Eureka監控頁面的System Status Data center
  environment: test            # 修改Eureka監控頁面的System Status Environment
  instance:
    hostname: localhost
    prefer-ip-address: true
    leaseRenewalIntervalInSeconds:  5 # 心跳間隔,5秒
    leaseExpirationDurationInSeconds: 10  # 沒有心跳的淘汰時間,10秒
    instance-id: ${spring.application.name}:${spring.cloud.client.ip-address}:${spring.application.instance_id:${server.port}} #SpringCloud 2.0 已經改成 ${spring.cloud.client.ip-address} 了,於是修改
  client:
    healthcheck:
      enabled: true
    # 默認情況下,eureka server同時也是eureka client,用於相互註冊形成高可用eureka服務。
    # 單點時,如果registerWithEureka配置爲true,則eureka server會報錯Cannot execute request on any known server
    registerWithEureka: false # 是否註冊到eureka服務,默認爲true,當前已爲eureka server,且單點eureka,故配置爲false
    fetchRegistry: false # eureka之間如果網絡不穩定,客戶端一般也會緩存了註冊列表,因此eureka服務可以不緩存,我覺得更能確保eureka之間的一致。
    serviceUrl:
      # registerWithEureka關閉後,defaultZone沒有配置的必要。如果打開,即使配置爲本機一樣報錯。
      # 也就是說defaultZone任何時候都沒有配置爲localhost的必要。這點上John的配置更好,永超和周立包括志朋的配置有點多餘。
      # 但是周立說的對,這個屬性默認配置是http://localhost:8761/eureka,也就是當你沒有用戶名密碼安全認證時,本機調試時,客戶端可以不配置,
      # 但對於server來說,這個默認沒有什麼作用。對於client來說,也只有調試的時候有點作用。
      # 但有一點很奇怪,既然默認了8761端口,爲什麼eureka server的默認端口要用8080而不是8761呢?
      defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/ #應用的主機名稱
  #      defaultZone: http://${security.user.name}:${security.user.password}@localhost:${server.port}/eureka # 本配置應刪除。
  server:
    # 自我保護機制,默認true。打開後,心跳失敗在15分鐘內低於85%(renewalPercentThreshold)的服務,也不進行剔除。
    # 關閉後,主頁提示:RENEWALS ARE LESSER THAN THE THRESHOLD. THE SELF PRESERVATION MODE IS TURNED OFF.
    # THIS MAY NOT PROTECT INSTANCE EXPIRY IN CASE OF NETWORK/OTHER PROBLEMS.
    enableSelfPreservation: true # 本地調試時可fasle關閉。但生產建議打開,可防止因網絡不穩定等原因導致誤剔除服務。
    renewalPercentThreshold: 0.85 # 默認85%
    # 在服務器接收請求之前等待的初始時間,默認等待5min(John Carnell)
    waitTimeInMsWhenSyncEmpty: 5 # John說開發時最好註釋此配置,服務註冊需要3次心跳,每次10s,也就是30s才能顯示在eureka。但是爲什麼我這裏馬上就顯示呢?
    # eureka server刷新readCacheMap的時間,注意,client讀取的是readCacheMap,這個時間決定了多久會把readWriteCacheMap的緩存更新到readCacheMap上
    # 默認30秒,eclipse提示默認0應該是錯誤的,源代碼中responseCacheUpdateIntervalMs = 30 * 1000。
    response-cache-update-interval-ms: 3000 # 網上很多專家的博客錯誤寫成responseCacheUpdateInvervalMs,請注意。這裏配置爲3秒。
    # eureka server緩存readWriteCacheMap失效時間,這個只有在這個時間過去後緩存纔會失效,失效前不會更新,
    # 過期後從registry重新讀取註冊服務信息,registry是一個ConcurrentHashMap。
    # 由於啓用了evict其實就用不太上改這個配置了,默認180s
    responseCacheAutoExpirationInSeconds: 180
    # 啓用主動失效,並且每次主動失效檢測間隔爲3s。源碼evictionIntervalTimerInMs = 60 * 1000,默認一分鐘。
    # 需要注意的是該配置會打印INFO日誌,增加info日誌量,修改後從每60秒打印一次變成3秒打印一次。
    evictionIntervalTimerInMs: 3000 # 注意不要寫成EvictionIntervalTimerInMs,yml大小寫敏感。

如果是多實例高可用修改下列配置

eureka:
  client:
    registerWithEureka: true # 是否註冊到eureka服務
    serviceUrl:
      defaultZone: http://peer2:1112/eureka/,http://peer3:1112/eureka/ #應用的主機名稱

客戶端

第一步加依賴

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

第二步加註解

//@EnableEurekaClient
@EnableDiscoveryClient
@SpringBootApplication
public class ClientApplication {
    public static void main(String[] args) {
        SpringApplication.run(ClientApplication.class, args);
    }
}

第三步寫配置

eureka:
  instance:
#    ip-address: #指定ip地址
    # 是否以IP註冊到Eureka Server上,如果false則不是IP而是服務器名稱
    # 但我設置了false,eureka主頁仍顯示192.168.100.16:client-microservice:8010
    preferIpAddress: true # 將IP註冊到Eureka Server上,而如果不配置就是機器的主機名。默認false。應該始終設置爲true。如果基於Docker等容器的部署,容器會生成一個隨機的主機名,此時DNS不存在該名,無法解析 - John Carnell
    # 實例名。SpringCloud體系裏的,服務實體向eureka註冊時,註冊名默認是“IP名:應用名:應用端口名”${spring.application.name}:${spring.cloud.client.ip-address}:${spring.application.instance_id:${random.int}}
    # 如果服務名,ip,端口都一致的話,eureka只顯示一個服務
    instance-id: ${spring.cloud.client.hostname}:${spring.application.name}:${spring.cloud.client.ip-address}:${spring.application.instance_id:${random.int[1,9]}}[email protected]@
    # 服務續約的兩個重要屬性
    leaseRenewalIntervalInSeconds: 30 # 服務續約間隔時間。默認每隔30秒,客戶端會向服務端發送心跳。見DiscoveryClient.initScheduledTasks
    leaseExpirationDurationInSeconds: 90 # 服務失效時間。缺省爲90秒服務端接收不到客戶端的心跳,則剔除該客戶端服務實例。
    # 端點配置。若配置了context-path,actuator的監控端點會增加前綴,此時eureka也需要相應增加
    #status-page-url-path: ${server.servlet.context-path}/actuator/info
    #health-check-url-path: ${server.servlet.context-path}/actuator/health

    #    Eureka 的元數據
    metadata-map:
      zc-data: Current services are goods services  # 不會影響客戶端
      zone: ABD               # Eureka可以理解的元數據,可以影響客戶端
#    appname: AAAAA            # 填坑 Swagger:配置和spring.application.name 衝突
  client:
    # eureka服務的位置,如配置錯誤,則:Cannot execute request on any known server
    # 詳見:com.netflix.discovery.endpoint.EndpointUtils
    service-url:
      defaultZone: http://localhost:8761/eureka/ #應用的主機名稱
    # 是否啓用eureka客戶端。默認true
    enabled: true # 本地調試時,若不想啓動eureka,可配置false即可,而不需要註釋掉@EnableDiscoveryClient這麼麻煩。感謝永超,從他的書知道這個屬性。
    # 支持registerWithEureka(John、周立)和register-with-eureka(翟永超)兩種寫法,eclipse的STS默認使用後者。
    # 基本所有配置使用橫槓或者駝峯都可以,鼠標放在上面,eclipse都可以顯示詳細註解和默認值(如果有)。
    registerWithEureka: true # 默認true,因此也可省略。
    fetchRegistry: true # 默認true,此處可不配置。
    # 緩存清單更新時間,默認30秒。見EurekaClientConfigBean,其中DefaultEurekaClientConfig可不看(前者spring實現,後者Netflix實現)
    registry-fetch-interval-seconds: 30 # 如果想eureka server剔除服務後儘快在client體現,我覺得可縮短此時間。
    # 周立在Camden SR4(對應eureka-client.jar1.2.6)中說有該屬性,但我在SR6(對應1.2.4)和SR4中都找不到;
    # 又查找了Brixton SR7(對應1.1.7,其實不光eureka-client,整個spring-cloud-netflix都是這個版本),也是沒有。
    # 這是因爲該屬性IDE確實不能提示,但寫法是正確的。作用是修改eureka的健康檢查方式(心跳),改爲用actuator,詳見HealthCheckHandler HealthIndicator。
    # 周立寫的不是太詳細,可詳見這博客:https://blog.csdn.net/xiao_jun_0820/article/details/77991963
    # 若配置healthcheck,需引入actuator。
    healthcheck:
      enabled: true # 我建議配置爲true。心跳機制有個問題,如當客戶端的數據庫連接出現問題導致不可用時,心跳機制不能反映,但actuator的health可以。

最後可以通過DiscoveryClient對象,在日誌中打印出服務實例的相關內容。

@Slf4j
@RestController
public class TestController {
    @Autowired
    private DiscoveryClient discoveryClient;

    @GetMapping("/getDiscoveryClient")
    public List<ServiceInstance> getDiscoveryClient() {
        return discoveryClient.getInstances("server-1");//獲取客戶端實例服務
    }

    @GetMapping("/getServices")
    public List<String> getServices() {
        return discoveryClient.getServices();
    }
}

趙小胖個人博客

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