寫在開頭,這篇不是小白教程,頂多算是碰坑記錄,甚至可能連問題都沒有描述清楚。html
由於之前弄過基於SpringBoot 1.X,因此忽略了一些基本配置,這個版本基於SpringBoot2.0.0,和1.X的沒有很大區別,網上挺多1.X配置的教程,搭建過程這裏不過多說明。java
主要搭建Netflit家族的幾個部分,包括配置服務器、Eureka服務註冊與發現、Ribbon負載均衡、Feign客戶端、Hystrix服務熔斷、Zuul網關等。git
由於懶得在git上建立配置文件,因此配置成從本地讀取配置文件:github
spring: profiles: active: native
也比較簡單,按照官方文檔搭建好註冊中心和服務,爲了使配置服務器有所做用,將服務端口放在配置服務器上的配置文件上。
主要是Eureka Server +Spring Security認證配置時出了問題,配置文件上:web
#1.X版本: security: basic: enabled: true user: name: password: #變成了: spring: security: basic: enabled: true user: name: password: #並且只要添加了Spring Security Starter依賴,spring.security.basic.enabled默認就是true,改爲false也沒用。
啓動起來,客戶端報異常:Cannot execute request on any known server。致使服務註冊失敗。
各類檢查配置,折騰了幾個小時也沒搞好,最後在GitHub上找到了答案【https://github.com/spring-cloud/spring-cloud-netflix/issues/2754】,原來是SpringBoot從2.0.0.RC1升級到2.0.0.RELEASE的時候,有個類SpringBootWebSecurityConfiguration發生了變化:spring
public class SpringBootWebSecurityConfiguration { @Configuration @Order(SecurityProperties.BASIC_AUTH_ORDER) static class DefaultConfigurerAdapter extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { super.configure(http);//新包這兩行被刪了 http.csrf().disable(); } } }
新建這個類放在Eureka Server項目裏面就能夠了;或者將SpringCloud降到Finchley.M6及如下,同時SpringBoot降級到2.0.0.RC1,只能說嚐鮮需謹慎。。。服務器
這個也沒什麼好說的,太簡單了。負載均衡
也沒什麼好說,官方把Feign改爲了OpenFeign,用法和1.X基本沒什麼區別。ide
在服務消費端規規矩矩改好配置,添加依賴:spring-boot
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-hystrix</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency>
啓動,又遇到坑了!!!
按照官方文檔訪問http://host:port/hystrix.stream 查看斷路由狀態發現是404,根本就沒有暴露hystrix.stream這個端點。又折騰了將近一個小時,纔在另一個文檔上找到答案:
https://docs.spring.io/spring-boot/docs/current/reference/html/production-ready-endpoints.html
原來是Actuator這個包變化了,默認只暴露health等幾個端點,好吧,把配置加上:
management: endpoints: web: exposure: include: hystrix.stream
啓動後觀察日誌發現暴露的服務url居然是/actuator/hystrix.stream,固然這也能夠用,若是不想要/actuator,添加如下配置便可:
management: endpoints: web: base-path: /
被SpringCloud官方文檔坑了一把。
回頭弄一下配置的刷新,配置服務器上的配置文件更新,其它服務能夠不重啓而獲取最新配置。
在服務消費端進行了修改,理所固然在post http://host:port/refresh 時又是404,有了上面hystrix.stream的教訓,立刻在配置上增長:
management: endpoints: web: exposure: include: refresh
OK,經過,配置刷新了。
單個服務刷新沒問題,再集成Spring Cloud Bus來批量刷新試試吧,這裏用了Kafka:<br/>
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-bus-kafka</artifactId> </dependency>
這下我聰明瞭先改配置文件把bus/refresh端點暴露出來,啓動,post http://host:port/bus/refresh ,404!!!
好吧,不要過於相信官方文檔,修改一下配置把全部端點暴露,觀察啓動日誌發現有一個bus-refresh,post一下 http://ip:port/bus-refresh ,bingo,是想要的東西。
沒遇到什麼問題了,主要是前面在服務上加了Spring Security,網關訪問服務須要加上認證信息,具體看本身實現的PreFilter。
確實變化不大,變的基本都在Actuator裏面了,陸陸續續隨手寫,後續再看要不要完善,順手貼上示例地址:
https://gitee.com/cionhome/SpringCloudDemo
參考:
官方文檔
Github