天天看點

SpringCloud報Cannot execute request on any known server或者Connection refused

一、Service-url:DefaultZone配置不對

我們在選擇SpringCloud的Eureka作為注冊中心,讓用戶端去注冊服務時經常會遇到因為一些配置的原因會報Cannot execute request on any known serve之類的錯誤。

本人用的SpringCloud的版本是Greenwich.SR1,Springboot是2.1.5的,這應該是在今年6月前最新的版本了。我在做服務的注冊與發現的時候,想把service-url的DefaultZone這項的位址改為自定義的位址,如:http://localhost:10240/Register/.然後把eureka Server啟動起來,程序沒問題;但是當在用戶端的Application.yml檔案中把Service-url:DefaultZone的值指定成Server端的位址,即:http://localhost:10240/Register/,如下是我的配置:

Server端:

server:
  port: 9000

eureka:
  instance:
    hostname: localhost
    instance-id: Register
  client:
    service-url:
      defaultZone: http://localhost:9000/Register
    fetch-registry: false
    register-with-eureka: false
#    設定通路安全性
           
Client端:      
server:
  port: 10240

eureka:
  client:
    service-url:
      defaultZone: http://localhost:9000/Register

spring:
  application:
    name: Login
           

此時,啟動用戶端就會報“無法在任何已知服務上執行請求”,或者“連接配接拒絕”(由于小弟對SpringCloud隻是剛剛才看了幾天,是以好些東西不太明白)。經過多翻試探之後,發現:Eureka的defaltZone的值,字尾隻有是以“/eureka”結尾,即需要把Server端與用戶端的service-url:defaultZone的值都統一改成:http://localhost:9000/eureka,再分别運作Server端,Client端,服務注冊與發現Okay了。

本人現在還沒有跟蹤出能自定義這個Service-url字尾的方法,這點還得求網上的大神指點。

二、Eureka服務在加入Security Authentication時

舊版本的Springclound在Eureka Server端加入Spring-Boot的Security包後,在Application.yml檔案裡配置上如下行:

security:

    user:

        name: username

        password: pwd

       basic:

           enable: true

并且在服務端,用戶端的Service-url:DefaultZone裡配置成http://username:[email protected]:9000/eureka貌似就可以實作Eureka的服務注冊請求加密了.但是在我使用的這個SprinCloud版本中,配置有所改動:原來的以Security開頭的配置都過期了,而且安全認證這塊預設就是開房的;運作Eureka Server端倒是能正常運作;但是當運作Client的時候,Client也會報“無法在任何已知服務上執行請求”,或者“連接配接拒絕”。

發生該問題的原因是SpringCloud在你往Maven裡添加Spring-boot-Stater-Security包時就已經預設開啟了密碼認證這一功能,而且,根據官網的描述,隻要開啟了這一安全認證,Eureka預設每一個對目前服務的請求都需要一個CSRF Token被随着發送過來,是以解決辦法是采用官網的推薦做法:擴充“WebSecurityConfigurerAdapter”類并重載Configure方法,攔截Http裡所有類似“/eureka/**”的請求,然後忽略它就行,同時需要在這個類上添加EnableWebSecurity注冊,如下:

@EnableWebSecurity
    public static class IgnoreEruekaClientSecurity extends WebSecurityConfigurerAdapter{
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.csrf().ignoringAntMatchers("/eureka/**");
            super.configure(http);
        }
    }
           

重新啟動Server與Client,服務就能成功注冊

繼續閱讀