09-SpringCloud 之 Zuul
阿新 • • 發佈:2022-05-29
什麼是 Zuul
Zuul 即:服務閘道器,它包含了對請求的路由和過濾兩個主要功能
Zuul 的使用
-
新建 Module:spring-cloud-zuul-9527
-
編寫 pom 引入依賴
pom.xml
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <parent> <artifactId>spring-cloud-netflix</artifactId> <groupId>com.kaishen</groupId> <version>1.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>spring-cloud-zuul-9527</artifactId> <properties> <maven.compiler.source>8</maven.compiler.source> <maven.compiler.target>8</maven.compiler.target> </properties> <!-- 引入該模組所需依賴 --> <dependencies> <!-- Eureka Client --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-eureka</artifactId> </dependency> <!-- zuul --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-zuul</artifactId> </dependency> </dependencies> </project>
-
編寫 application.yml 配置路由及攔截
Zuul 也需要註冊到 Eurekaapplication.yml
server: port: 9527 # Spring 配置 spring: application: name: spring-cloud-zuul # Eureka 配置 eureka: client: service-url: defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/ instance: instance-id: www.zuul9527.com # 服務描述資訊 prefer-ip-address: true # 顯示 ip 地址 # 監控資訊 info: app.name: kaishen-spring-cloud-zuul9527 # Zuul 配置 zuul: routes: mydept.serviceId: spring-cloud-provider-dept # 微服務名,對 9527 的訪問將會被路由到該服務 mydept.path: /mydept/** # url 地址攔截 ignored-services: spring-cloud-provider-dept # 忽略,即不能使用微服務名進行訪問 ("*" 表示隱藏所有微服務) prefix: /kaiye/ # 訪問字首
-
編寫啟動類,開啟註解
ZuulApplication9527
package com.kaishen; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.zuul.EnableZuulProxy; /** * 路由閘道器啟動類 * @author : toby * Create in 17:46 2022/5/9 */ @SpringBootApplication @EnableZuulProxy public class ZuulApplication9527 { public static void main(String[] args) { SpringApplication.run(ZuulApplication9527.class, args); } }
-
訪問:
在 C:\Windows\System32\drivers\etc\hosts 中配置主機對映,即可使用http://www.kaishen.com:9527/kaiye/mydept/dept/get/1
訪問後端服務