前言
在我們前面的博客中講到,當服務A需要調用服務B的時候,只需要從Eureka中獲取B服務的注冊實例,然后使用Feign來調用B的服務,使用Ribbon來實現負載均衡,但是,當我們同時向客戶端暴漏多個服務的時候,客戶端怎么調用我們暴漏的服務了,如果我們還想加入安全認證,權限控制,過濾器以及動態路由等特性了,那么就需要使用Zuul來實現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服務注冊到Eureka Server上,同時從Eureka Server上發現注冊的服務,所以這里我們加上了Eureka的依賴。
二、在應用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的基礎配置信息
1
2
3
4
5
6
7
8
9
10
11
|
spring: application: name: gateway-zuul # 應用名 server: port: 8768 #Zuul Server的端口號 eureka: client: service-url: defaultZone: http://localhost:8761/eureka instance: prefer-ip-address: true |
四、在application.yml中增加服務路由配置
前提:在Eureka Server已經注冊了2個服務,分別是:springboot-h2-service和springboot-rest-template-feign,其中springboot-rest-template-feign服務會調用springboot-h2-service服務,springboot-rest-template-feign服務是我們對外提供的服務,也就是說,springboot-rest-template-feign服務是我們暴漏給客戶端調用的。
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的請求,都會被攔截,并且轉發到templateservice上 # 路由配置方式二 zuul: routes: api-contract: # 其中api-contract是路由名稱,可以隨便定義,但是path和service-id需要一一對應 path: /templateservice/** service-id: springboot-rest-template-feign # springboot-rest-template-feign為注冊到Eureka上的服務名 ribbon: NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RoundRobinRule # 配置服務端負載均衡策略 |
五、驗證
下面我們就可以來進行驗證了,在瀏覽器中輸入:http://localhost:8768/templateservice/template/1就可以看到測試結果了。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:http://blog.csdn.net/liuchuanhong1/article/details/59056278