sb2.0新版springcloud微服務實戰:Eureka+Zuul+Feign/Ribbon+Hystrix Turbine+SpringConfig+sleuth+zipkinjava
springboot 版本是 2.0.3.RELEASE ,springcloud 版本是 Finchley.RELEASEnginx
本篇文章是springboot2.x升級後的升級springcloud專貼,由於以前版本更新已經很久了,好多人評論可不能夠出個新版本,你們必定要注意,這是springboot2.x版本的,springboot1.x的請參考 點擊查看文章,基本組件都不變就是升級jar包版本,主要就是hystrix-dashboard使用有點變化。還有一點要注意的是sc默認使用的是eureka1.9.x版本,你們必定要主要,不要本身手動改成2.x版本,由於2.x版本尚未正式發佈,並且中止開發了,官方還在積極的維護1.x版本(並非網傳的閉源)。git
相信如今已經有不少小夥伴已經或者準備使用springcloud微服務了,接下來爲你們搭建一個微服務框架,後期能夠本身進行擴展。會提供一個小案例: 服務提供者和服務消費者 ,消費者會調用提供者的服務,新建的項目都是用springboot,附源碼下載,推薦使用coding地址下載,由於能夠切換分支,後期能夠及時更新。web
coding倉庫地址(推薦下載): coding地址 遠程配置倉庫地址 遠程配置倉庫地址面試
若是有問題請在下邊評論,或者200909980加羣交流。或者關注文章結尾微信公衆號,私信後臺spring
Eureka/Consul/Zookeeper:服務發現 (根據狀況選擇一個,eureka已經宣佈閉源)數據庫
Hystrix:斷路器bootstrap
Zuul:智能路由後端
Ribbon/Feign:客戶端負載均衡 (Feign用的更多)數組
Turbine&hystrix-dashboard:集羣監控
Springcloud-config:遠程獲取配置文件
接下來,咱們開始搭建項目,首先咱們到spring爲咱們提供的一個網站快速搭建springboot項目,點擊訪問,我這裏用的是gradle,若是各位客官喜歡用maven,好吧你能夠到http://mvnrepository.com/查看對應的依賴,點我訪問。
1.png
1、搭建eureka-server服務sc-eureka-server
使用 spring-cloud-consul 做爲服務發現 請參考 點擊查看使用springcloud consul 做爲服務發現
eureka-server做爲服務發現的核心,第一個搭建,後面的服務都要註冊到eureka-server上,意思是告訴eureka-server本身的服務地址是啥。固然還能夠用zookeeper或者springconsul。
1.修改build.gradle文件 若是是maven項目請對應的修改pom.xml
//加入阿里的私服倉庫地址 maven { url "maven.aliyun.com/nexus/conte…" } //加入依賴 compile('org.springframework.cloud:spring-cloud-starter-netflix-eureka-server') //加入security,是由於訪問eureka-server須要用戶名和密碼訪問,爲了安全 compile('org.springframework.boot:spring-boot-starter-security') 還有幾點須要修改的,你們對應圖片看看,就是springboot打包的時候會提示找不到主類。
2.png
2.修改 application.yml,建議用yml。 server: port: 8761 eureka: datacenter: trmap environment: product server:
enable-self-preservation: false
eviction-interval-timer-in-ms: 5000 client: healthcheck: enabled: true service-url: defaultZone: http://root:booszy@localhost:8761/eureka/ register-with-eureka: false fetch-registry: false spring: security: basic: enabled: true user: name: root password: booszy 3.修改程序的主類,建議修改類名,要加如eureka的 @EnableEurekaServer 註解,而後運行main方法。 @EnableEurekaServer @SpringBootApplication public class Sb2scEurekaApplication { public static void main(String[] args) { SpringApplication.run(Sb2scEurekaApplication.class, args); } }
4.png
http://localhost:8761/ 這個是eureka-server的頁面地址,密碼在yml配置文件中,到這裏,說明eureka-server搭建好了,簡單吧,這一步必定要成功,不然後面的就不能繼續進行下去了,後邊基本相似。
2、搭建config-server服務sc-config-server
springcloud-config-server是用來將遠程git倉庫的配置文件動態拉下來,這樣配置文件就能夠動態的維護了。固然也能夠選擇本地倉庫。
新建一個springboot項目,修改maven私服地址,並加入一下依賴。
1.修改build.gradle文件 compile('org.springframework.cloud:spring-cloud-config-server') compile('org.springframework.cloud:spring-cloud-starter-netflix-eureka-client') //鏈接config-server也須要用戶名和密碼 compile('org.springframework.boot:spring-boot-starter-security') compile('org.springframework.boot:spring-boot-starter-actuator') 2.修改application.yml文件 server: port: 8800 spring: security: basic: enabled: true user: name: root password: booszy application: name: sc-config-server cloud: config: server: git: uri: git.coding.net/yirenyishi/… searchPaths: '{application}' eureka: client: service-url: defaultZone: http://root:booszy@localhost:8761/eureka/ instance: prefer-ip-address: true instance-id: {spring.application.instance_id:${server.port}} appname: sc-config-server 3.修改啓動類 修改啓動類,要加入這三個註解,由於要註冊到eureka-server上,因此須要@EnableDiscoveryClient這個註解
@EnableConfigServer
@EnableDiscoveryClient
@SpringBootApplication
public class Sb2scConfigApplication {
public static void main(String[] args) {
SpringApplication.run(Sb2scConfigApplication.class, args);
}
}
而後運行啓動springboot項目,等啓動成功後訪問eureka的頁面,會發現sc-config-server已經註冊到上面了,若是啓動報錯,請檢查錯誤信息。
3.png
3、搭建服務提供者服務sc-provider
編寫一個服務提供者,爲下邊的消費者提供服務,用到了spring-webflux(spring新出的非阻塞式框架)不是springmvc,固然大家公司用什麼你仍是繼續用什麼。
注意 : 這裏除了application.xml,還須要一個bootstrap.yml, 由於bootstrap.yml得加載順序是在application.xml前邊,服務註冊和config配置必須放到bootstrap.yml。 修改build.gradle文件 compile('org.springframework.cloud:spring-cloud-starter-netflix-eureka-client') compile('org.springframework.cloud:spring-cloud-starter-config') compile('org.springframework.boot:spring-boot-starter-webflux') compile('org.springframework.boot:spring-boot-starter-actuator') 2.編寫配置文件bootstrap.yml ** 注意 : 這裏除了application.xml,還須要一個bootstrap.yml*
application.xml我是放到遠程倉庫地址的,你們能夠直接到個人遠程倉庫,根據項目名(sc-provider-config)查詢。配置文件的倉庫地址:點擊訪問。
eureka: client: service-url: defaultZone: http://root:booszy@localhost:8761/eureka/ instance: prefer-ip-address: true instance-id: {spring.application.instance_id:${server.port}} appname: sc-provider spring: application: name: sc-provider cloud: config: discovery: enabled: true service-id: sc-config-server fail-fast: true username: root password: booszy profile: csdn 3.編寫代碼 編寫主類
@EnableDiscoveryClient @SpringBootApplication public class Sb2scProviderApplication { public static void main(String[] args) { SpringApplication.run(Sb2scProviderApplication.class, args); } } 新建IndexController進行測試,這裏只是爲了測試,案例代碼使用的是webflux,若是想使用springmvc,修改jar包依賴便可。
@RestController @RequestMapping("test") public class IndexController { //返回一個實體 @GetMapping("{msg}") public Mono sayHelloWorld(@PathVariable("msg") String msg) { System.out.println("come on " + msg); return Mono.just("sc-provider receive : " +msg); } //返回一個列表 @GetMapping("list") public Flux list() { List list = new ArrayList<>(); list.add(8); list.add(22); list.add(75); list.add(93); Flux userFlux = Flux.fromIterable(list); return userFlux; } } 運行springboot項目,去eureka-server查看,有沒有註冊上。
5.png
咱們的sc-provider已經註冊到eureka上了,訪問接口,成功。
6.png
4、搭建消費者服務sc-consumer
消費者要訪問服務提供者的服務,這裏用的是經過RestTemplate/feign請求resetful接口,使用ribbon作客戶端負載均衡,hystrix作錯誤處理,feign和ribbon二選一,案例中ribbon和feign都有,也能夠都用。
仍是熟悉的配方,熟悉的味道,新建springboot項目,添加項目依賴。
1.修改build.gradle文件 compile('org.springframework.cloud:spring-cloud-starter-netflix-eureka-client') compile('org.springframework.cloud:spring-cloud-starter-config') compile('org.springframework.boot:spring-boot-starter-webflux') compile('org.springframework.boot:spring-boot-starter-actuator') compile('org.springframework.cloud:spring-cloud-starter-openfeign') compile('org.springframework.cloud:spring-cloud-starter-netflix-hystrix') 2.修改bootstrap.yml文件 application.yml 在git倉庫,請前往git倉庫查看。
eureka: client: service-url: defaultZone: http://root:booszy@localhost:8761/eureka/ instance: prefer-ip-address: true instance-id: {spring.application.instance_id:${server.port}} appname: sc-consumer spring: application: name: sc-consumer cloud: config: discovery: enabled: true service-id: sc-config-server fail-fast: true username: root password: booszy profile: csdn #新版配置,不然後面dashboard沒法找到hystrix.stream management: endpoints: web: exposure: include: '*' 3.編寫代碼 啓動類代碼
@RibbonClient 指定服務使用的負載均衡類型,name不指定服務則爲全部的服務打開負載均衡,也能夠在用yml中進行配置。
@EnableHystrix 是支持hystrix打開斷路器,在規定時間內失敗參數超過必定參數,就會打開斷路器,不會發起請求,而是直接進入到錯誤處理方法。
@EnableDiscoveryClient @EnableFeignClients @EnableCircuitBreaker @EnableHystrix @SpringBootApplication public class Sb2scConsumerApplication { // ribbon須要配置,負載均衡 @Autowired private RestTemplateBuilder builder; // ribbon須要配置,負載均衡 @Bean @LoadBalanced public RestTemplate restTemplate() { return builder.build(); } public static void main(String[] args) { SpringApplication.run(Sb2scConsumerApplication.class, args); } } 1.ribbon案例
ribbon不須要單獨依賴,新建 RibbonController
ribbon一個坑,不能接受List類型,要使用數組接收。
@HystrixCommand(fallbackMethod="fallbackMethod")
若是請求失敗,會進入fallbackMethod這個方法,fallbackMethod這個方法要求參數和返回值與回調他的方法保持一致。
@RestController public class RibbonController { @Autowired private RestTemplate restTemplate; @Autowired private LoadBalancerClient loadBalancerClient; @GetMapping("/ribbon/{wd}") @HystrixCommand(fallbackMethod="fallbackMethod") public Mono sayHelloWorld(@PathVariable("wd") String parm) { String res = this.restTemplate.getForObject("http://sc-provider/test/" + parm, String.class); return Mono.just(res); } public Mono fallbackMethod(@PathVariable("wd") String parm) { return Mono.just("fallback"); } 運行springboot項目,先看有沒有註冊到eureka-server上。
7.png
註冊成功後,訪問接口,測試是否正確。
8.png
ribbon使用就是這麼簡單,ribbon是springboot自帶,因此不須要單獨添加依賴。
2.feign案例
在實際開發中,feign使用的仍是挺多的,feign底層仍是使用了ribbon。廢話很少說,直接上步驟,在服務消費者中使用feign訪問服務提供者。
1配置文件 ribbon: ReadTimeout: 30000 ConnectTimeout: 15000 hystrix: command: default: execution: isolation: thread: timeoutInMilliseconds: 10000 feign的默認請求超時時間是1s,因此常常會出現超時的問題,這裏我設置的是10s,由於個人數據庫服務器在美國,因此有時候請求會比較慢。ribbon的請求時間也要設置,由於feign用的是ribbon。這裏貼的是application.yml文件中的一小段
2 編碼 一、主類註解
@EnableFeignClients
@EnableCircuitBreaker
@EnableHystrix
這三個都要,hystrix主要做用是斷路器,會進如fein的fallback中。 主類代碼在上面已經貼出來了
二、編寫feign接口,MFeignClient.class
name是指要請求的服務名稱。這裏請求的是服務提供者
fallback 是指請求失敗,進入斷路器的類,和使用ribbon是同樣的。
configuration 是feign的一些配置,例如編碼器等。
@FeignClient(name = "sc-provider",fallback = MFeignClientFallback.class, configuration = MFeignConfig.class) public interface MFeignClient { // 這是被請求微服務的地址,也就是provider的地址 @GetMapping(value = "/test/{msg}") String sayHelloWorld(@PathVariable("msg") String msg); @GetMapping(value = "/test/list") List list(); @GetMapping(value = "/test/list") Integer[] array(); } 3 MFeignConfig.class feign的配置 這裏配置了feign的打印日誌等級
@Configuration public class MFeignConfig { @Bean Logger.Level feignLoggerLevel() { return Logger.Level.FULL; } } 4 MFeignClientFallback.class ,斷路器回調方法 斷路器要實現上邊定義的MFeignClient接口,請求失敗,進入斷路器時,會回調這裏的方法。
@Component public class MFeignClientFallback implements MFeignClient{ @Override public String sayHelloWorld(String msg) { return "fallback"; } @Override public List list() { return new ArrayList<>(); } @Override public Integer[] array() { return new Integer[0]; } } 5 在controller中使用feign @RestController public class FeignController { @Autowired private MFeignClient feignClient; @GetMapping("/feign/{wd}") public Mono sayHelloWorld(@PathVariable("wd") String parm) { String result = feignClient.sayHelloWorld(parm); return Mono.just(result); } @GetMapping("/feign/list") public Flux list() { List list = feignClient.list(); Flux userFlux = Flux.fromIterable(list); return userFlux; } @GetMapping("/feign/array") public Flux array() { Integer[] arrays = feignClient.array(); Flux userFlux = Flux.fromArray(arrays); return userFlux; } }
9.png
5、用zuul作路由轉發和負載均衡
這些微服務都是隱藏在後端的,用戶是看不到,或者不是直接接觸,能夠用nginx或者zuul進行路由轉發和負載均衡,zuul負載均衡默認用的是ribbon。
1.修改build.gradle文件 compile('org.springframework.cloud:spring-cloud-starter-netflix-eureka-client') compile('org.springframework.cloud:spring-cloud-starter-config') compile('org.springframework.cloud:spring-cloud-starter-netflix-zuul') compile('org.springframework.boot:spring-boot-starter-actuator') 2.修改bootstrap.yml 仍是原來的配方,application.yml在git倉庫
eureka: client: service-url: defaultZone: http://root:booszy@localhost:8761/eureka/ instance: prefer-ip-address: true instance-id: {spring.application.instance_id:${server.port}} appname: sc-zuul spring: application: name: sc-zuul cloud: config: discovery: enabled: true service-id: sc-config-server fail-fast: true username: root password: booszy profile: csdn 3.啓動類 @RefreshScope這個註解是當application.yml配置文件發生變化的時候,不須要手動的進行重啓,調用localhost:8400/refresh,就會加載新的配置文件,固然正在訪問的客戶並不影響仍是使用舊的配置文件,由於不是重啓,後來的用戶會使用新的配置文件。注意這塊的刷新要用post請求。
@EnableDiscoveryClient @SpringBootApplication @EnableZuulProxy @RefreshScope public class Sb2scZuulApplication { public static void main(String[] args) { SpringApplication.run(Sb2scZuulApplication.class, args); } } 啓動springboot項目,訪問eureka-server
10.png
這時候,咱們就要經過zuul訪問微服務了,而不是直接去訪問微服務。
應該訪問地址http://localhost:8400/sc-consumer/feign/list,這塊你要換成你的zuul地址。
可是有些人就會說,這樣之後用戶請求會不會太長,比較反感,因此能夠經過配置進行修改訪問地址。
zuul: routes: springcloud-consumer-config: /consumer/** springcloud-provider-config: /provider/** 在application.yml中加入這樣一段配置,其實就是nginx中的反向代理,使用一下簡短的能夠代理這個微服務。這個時候咱們就能夠這樣去訪問了http://localhost:8400/consumer/feign/list,是否是簡短了不少
11.png
6、用hystrix-turbine-dashboard 作集羣監控
項目在生產環境中,每一個服務的訪問量都不通,有些服務的訪問量比較大,有時候有些服務掛了,不能繼續服務,須要重啓的時候,咱們並不知道,因此這時候就須要使用hystrix-turbine-dashboard作一個監控,監控全部的微服務,能夠看到這個接口實時訪問量,和健康情況。
新建一個springboot項目,老套路,加入以下依賴
1 添加依賴 compile('org.springframework.cloud:spring-cloud-starter-netflix-eureka-client') compile('org.springframework.boot:spring-boot-starter-actuator') compile('org.springframework.cloud:spring-cloud-starter-netflix-hystrix') compile('org.springframework.cloud:spring-cloud-starter-netflix-hystrix-dashboard') compile('org.springframework.cloud:spring-cloud-starter-netflix-turbine') 2 修改application.yml配置文件 注意:是application.yml,這裏不須要bootstrap.yml server: port: 8900 eureka: client: service-url: defaultZone: http://root:booszy@localhost:8761/eureka/ instance: prefer-ip-address: true instance-id: {spring.application.instance_id:${server.port}} appname: sc-dashboard turbine: aggregator: clusterConfig: default appConfig: sc-consumer clusterNameExpression: "'default'" spring: application: name: sc-dashboard #management:
appConfig 後面是要檢測的註冊在eureka上的服務名,必需要有
3 修改主類 @EnableTurbine ,@EnableHystrixDashboard 一個都不能少
@EnableDiscoveryClient @SpringBootApplication @EnableTurbine @EnableHystrixDashboard public class Sb2scDashboardApplication { public static void main(String[] args) { SpringApplication.run(Sb2scDashboardApplication.class, args); } } 4 訪問測試 這塊的端口是8900,訪問地址http://localhost:8900/hystrix,看到的是下面的頁面。
13.png
而後在那個網址的輸入框裏輸網址http://localhost:8900/turbine.stream,點擊monitor stream。剛打開的時候多是空的,什麼也沒有,這並不表示你已經錯了。這時候你訪問消費者服務的接口,例如訪問http://localhost:8400/consumer/feign/list,多訪問幾回,而後看控制檯有沒有出現一個監控面板,沒有就等會刷新一次,若是一直不出現,應該是配置有問題。
12.png
7、使用sleuth+zipkin 實現鏈路追蹤服務
在使用微服務的時候,咱們發現,有時候排錯很差排查,因此就給你們整個這個鏈路追蹤,很方便知道是哪個服務調用哪個服務出現了問題。由於有些項目可能服務比較多。
1 添加依賴 新建一個springboot項目
雖然其餘服務調用zipkin不是從eureka上動態過去服務地址,而是硬編碼,可是這塊仍是考慮吧zipkin註冊到eureka上。
compile('org.springframework.cloud:spring-cloud-starter-netflix-eureka-client') compile group: 'io.zipkin.java', name: 'zipkin-server', version: '2.9.3' compile group: 'io.zipkin.java', name: 'zipkin-autoconfigure-ui', version: '2.9.3' compile('org.springframework.boot:spring-boot-starter-actuator') 若是提示log4j有衝突,要排除依賴
configurations { compile.exclude module: 'log4j' compile.exclude module: 'slf4j-log4j12' compile.exclude module: 'spring-boot-starter-logging' } 2 修改application配置文件 server: port: 9411 spring: application: name: sc-sc-zipkin profiles: active: csdn eureka: client: service-url: defaultZone: http://root:booszy@localhost:8761/eureka/ instance: prefer-ip-address: true instance-id: {spring.application.instance_id:${server.port}} appname: sc-zipkin management: metrics: web: server: auto-time-requests: false 3 主類註解添加 @EnableZipkinServer 主要是這個註解
啓動服務後訪問http://localhost:9411,就能夠打開zipkin的控制檯頁面,這時候應該是什麼都沒有
@EnableDiscoveryClient @SpringBootApplication @EnableZipkinServer public class Sb2scZipkinApplication { public static void main(String[] args) { SpringApplication.run(Sb2scZipkinApplication.class, args); } } 4 其餘服務中調用 這裏咱們在消費者服務和提供者服務裏都加入以下依賴
.... compile group: 'org.springframework.cloud', name: 'spring-cloud-starter-sleuth', version: '1.3.1.RELEASE' compile group: 'org.springframework.cloud', name: 'spring-cloud-sleuth-zipkin', version: '1.3.1.RELEASE' ... 而後修改配置文件,bootstrap.yml、
這塊zipkin的地址是硬編碼的,目前還沒發現怎麼從服務註冊中心eureka上動態獲取,之後有解決方案,會更新帖子
sleuth這個是配置提取率,能夠配置也能夠不配置
spring: zipkin: base-url: http://localhost:9411 sleuth: sampler: percentage: 1.0 啓動服務,而後訪問消費者服務的接口,這時候訪問zipkin的控制檯http://localhost:9411
14.png
點擊依賴分析,能夠看到調用服務鏈,由於這塊只涉及到兩個服務,因此只有兩個,在實際生產環境中,這塊可能有不少,到時候看起來就特別直觀了。
15.png
一、具備1-5工做經驗的,面對目前流行的技術不知從何下手,須要突破技術瓶頸的能夠加羣。
二、在公司待久了,過得很安逸,但跳槽時面試碰壁。須要在短期內進修、跳槽拿高薪的能夠加羣。
三、若是沒有工做經驗,但基礎很是紮實,對java工做機制,經常使用設計思想,經常使用java開發框架掌握熟練的,能夠加羣。
四、以爲本身很牛B,通常需求都能搞定。可是所學的知識點沒有系統化,很難在技術領域繼續突破的能夠加羣。
5.羣號Java架構交流羣 668041364
6.阿里Java高級大牛直播講解知識點,分享知識,上面六大專題都是各位老師多年工做經驗的梳理和總結,帶着你們全面、科學地創建本身的技術體系和技術認知! 。