前言
在我們前面的博客中講到,當服務A需要調用服務B的時候,只需要從Eureka中獲取B服務的註冊實例,然後使用Feign來調用B的服務,使用Ribbon來實現負載均衡,但是,當我們同時向客戶端暴漏多個服務的時候,客戶端怎麼調用我們暴漏的服務了,如果我們還想加入安全認證,權限控制,過濾器以及動態路由等特性了,那麼就需要使用Zuul來實現API GateWay了,下面,我們先來看下Zuul怎麼使用。
一、加入Zuul的依賴
<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支持
@SpringBootApplication @EnableZuulProxy // 使用@EnableZuulProxy來開啟Zuul的支持,如果你不想使用Zuul提供的Filter和反向代理的功能的話,此處可以使用@EnableZuulServer註解public class ZuulApplication { public static void main(String[] args) { SpringApplication.run(ZuulApplication.class, args); } }三、在application.yml中增加Zuul的基礎配置信息
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服務是我們暴漏給客戶端調用的。
# 路由配置方式一#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就可以看到測試結果了。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。