前言
在我們前面的博客中講到,當(dāng)服務(wù)A需要調(diào)用服務(wù)B的時候,只需要從Eureka中獲取B服務(wù)的注冊實例,然后使用Feign來調(diào)用B的服務(wù),使用Ribbon來實現(xiàn)負載均衡,但是,當(dāng)我們同時向客戶端暴漏多個服務(wù)的時候,客戶端怎么調(diào)用我們暴漏的服務(wù)了,如果我們還想加入安全認證,權(quán)限控制,過濾器以及動態(tài)路由等特性了,那么就需要使用Zuul來實現(xiàn)API GateWay了,下面,我們先來看下Zuul怎么使用。
一、加入Zuul的依賴
1
2
3
4
5
6
7
8
|
< dependency > < groupId >org.springframework.cloud</ groupId > < artifactId >spring-cloud-starter-zuul</ artifactId > </ dependency > < dependency > < groupId >org.springframework.cloud</ groupId > < artifactId >spring-cloud-starter-eureka</ artifactId > </ dependency > |
由于,我們需要將Zuul服務(wù)注冊到Eureka Server上,同時從Eureka Server上發(fā)現(xiàn)注冊的服務(wù),所以這里我們加上了Eureka的依賴。
二、在應(yīng)用Application主類上開啟Zuul支持
1
2
3
4
5
6
7
|
@SpringBootApplication @EnableZuulProxy // 使用@EnableZuulProxy來開啟Zuul的支持,如果你不想使用Zuul提供的Filter和反向代理的功能的話,此處可以使用@EnableZuulServer注解 public class ZuulApplication { public static void main(String[] args) { SpringApplication.run(ZuulApplication. class , args); } } |
三、在application.yml中增加Zuul的基礎(chǔ)配置信息
1
2
3
4
5
6
7
8
9
10
11
|
spring: application: name: gateway-zuul # 應(yīng)用名 server: port: 8768 #Zuul Server的端口號 eureka: client: service-url: defaultZone: http://localhost:8761/eureka instance: prefer-ip-address: true |
四、在application.yml中增加服務(wù)路由配置
前提:在Eureka Server已經(jīng)注冊了2個服務(wù),分別是:springboot-h2-service和springboot-rest-template-feign,其中springboot-rest-template-feign服務(wù)會調(diào)用springboot-h2-service服務(wù),springboot-rest-template-feign服務(wù)是我們對外提供的服務(wù),也就是說,springboot-rest-template-feign服務(wù)是我們暴漏給客戶端調(diào)用的。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
# 路由配置方式一 #zuul: # routes: # springboot-rest-template-feign: /templateservice/** #所有請求springboot-rest-template-feign的請求,都會被攔截,并且轉(zhuǎn)發(fā)到templateservice上 # 路由配置方式二 zuul: routes: api-contract: # 其中api-contract是路由名稱,可以隨便定義,但是path和service-id需要一一對應(yīng) path: /templateservice/** service-id: springboot-rest-template-feign # springboot-rest-template-feign為注冊到Eureka上的服務(wù)名 ribbon: NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RoundRobinRule # 配置服務(wù)端負載均衡策略 |
五、驗證
下面我們就可以來進行驗證了,在瀏覽器中輸入:http://localhost:8768/templateservice/template/1就可以看到測試結(jié)果了。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:http://blog.csdn.net/liuchuanhong1/article/details/59056278