Spring Cloud 教程 - Eureka Server

如何使用Eureka Server

將groupId 爲 org.springframework.cloud,artifactId 爲spring-cloud-starter-netflix-eureka-server的依賴添加到項目中即可引入Eureka Server,具體版本號可以參考Spring Cloud Project 使用如下代碼快速啓動Eureka Server

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

}

Server 包含一個主頁和其他的HTTP API,默認在/eureka/*路徑下。

 高可用,Zones和Regions

Eureka並不包含存儲,但是所有的服務實例必須發送心跳信息來更新啊們的狀態,這些信息都是在內存中操作的。客戶端同樣也包含一個Eureka的註冊信息。 默認情況下,一個Eureka的Server同樣也是一個Eureka的Client,需要配置Service URL來定位對方。

獨立模式

由於Server和Client緩存的存在,使得獨立模式下的Eureka對於失敗更具有彈性,只要有其他的監控或者彈性運行時保證其可用 接口。在獨立模式下,可以選擇關閉Client想問,這樣Client就不會持續嘗試獲取其他斷點,例如:

server:
  port: 8761eureka:
  instance:
    hostname: localhost
  client:
    registerWithEureka: false
    fetchRegistry: false
    serviceUrl:
      defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
對等模式

通過多實例互相註冊,可以使得Eureka更具彈性和可靠性。例如:

---
spring:
  profiles: peer1
eureka:
  instance:
    hostname: peer1
  client:
    serviceUrl:
      defaultZone: http://peer2/eureka/---
spring:
  profiles: peer2
eureka:
  instance:
    hostname: peer2
  client:
    serviceUrl:
      defaultZone: http://peer1/eureka/

配置兩個Eureka Server,這兩個Server互相註冊。

使用IP地址註冊

通過設置eureka.instance.preferIpAddress=true 開啓IP地址註冊,設置後,Eureka Client會使用IP註冊器服務而不是其hostname。

爲Eureka Server添加安全認證

可以通過spring-boot-starter-sercurity對Eureka Server添加安全認證。默認情況下,將其添加到classpath後,會對每個請求進行CSRF檢查。Eureka並不會生成CSRF token,所以需要關掉對/eureka/*路徑下的檢查:

@EnableWebSecurityclass WebSecurityConfig extends WebSecurityConfigurerAdapter {    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().ignoringAntMatchers("/eureka/**");        super.configure(http);
    }
}

用戶認證可以通過設置如下開啓

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