Spring Cloud學習筆記19——如何整合 Zuul
阿新 • • 發佈:2018-11-16
Zuul的功能
整合Zuul
開發環境
JDK8+
Gradle4+
Redis 3.2.100
Spring Boot 2.0.0.M3
Spring Cloud Starter Netflix Eureka Client Finchley.M2
Spring Cloud Starter Netflix Zuul Finchley.M2
建立專案
以之前的micro-weather-eureka-client
為藍本,建立micro-weather-eureka-client-zuul
專案
修改原始碼
修改build.gradle
Zuul
依賴:
//依賴關係
dependencies {
//Eureka Client
compile('org.springframework.cloud:spring-cloud-starter-netflix-eureka-client')
//Zuul
compile('org.springframework.cloud:spring-cloud-starter-netflix-zuul')
//該依賴用於測試階段
testCompile('org.springframework.boot:spring-boot-starter-test' )
}
修改com.study.spring.cloud.weather
包下的Application
類,加入@EnableZuulProxy
註解:
package com.study.spring.cloud.weather; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.netflix.zuul.EnableZuulProxy; /* * @SpringBootApplication註解宣告Spring Boot應用 * 作用等同於@Configuration, @EnableAutoConfiguration, @ComponentScan, * 簡化Spring配置 */ @SpringBootApplication //啟用可發現的客戶端 @EnableDiscoveryClient //啟用Zuul的代理功能 @EnableZuulProxy //Application類一定要處於整個工程的根目錄下,這樣它才能根據配置去掃描子節點下的Spring的Bean public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
修改application.properties
配置檔案:
#應用名稱
spring.application.name=micro-weather-eureka-client-zuul
#註冊伺服器的URL
eureka.client.service-url.defaultZone=http://localhost:8761/eureka/
#zuul本身的配置
#設定需要路由的URL,此處設定hi資源的路徑
zuul.routes.hi.path=/hi/**
#訪問hi應用時將請求轉發到某應用的應用名稱
zuul.routes.hi.service-id=micro-weather-eureka-client
執行
先通過IDE
執行micro-weather-eureka-server
再通過命令列編譯、執行micro-weather-eureka-client
,注意指定執行埠(如8081
),完成後可訪問http://localhost:8081/hello
頁面:
最後通過IDE
執行micro-weather-eureka-client-zuul
,執行結果如下:
訪問http://localhost:8080/hello
頁面:
訪問http://localhost:8080/hi/hello
頁面: