基於spring-cloud-zuul的路由閘道器設定
阿新 • • 發佈:2018-11-26
由於微服務的日益增多,管理也會不方便,所以需要一個可以集中管理所有服務的功能(類似sevelet的filter),可以在此做同一的許可權入口管理
新建一個模組spring-cloud-gateway
增加zuul及相關依賴如下:
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">
<modelVersion>4.0.0</modelVersion>
<artifactId>spring-cloud-gateway</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<properties>
< project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
<file.encoding>UTF8</file.encoding>
<spring-cloud.version>Finchley.SR2</spring-cloud.version>
</properties>
<parent>
< groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.2.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-zuul</artifactId>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
application.properties
server.port=8886
spring.application.name=gateway-service
eureka.client.service-url.defaultZone=http://localhost:8881/eureka/
#呼叫路徑服務的路徑
zuul.routes.eureka-client.path=/eureka-client/**
#呼叫服務的連結(不推薦,失去了均衡負載功能,只能使用一個服務)
#zuul.routes.lisiHello.url=http://localhost:8882/
#呼叫服務的id,即呼叫服務的名稱 spring.application.name
zuul.routes.eureka-client.serviceId=eureka-client
主方法只需要新增相關注解即可
application.java
package top.littlematch.gateway;
import org.springframework.boot.SpringApplication;
import org.springframework.cloud.client.SpringCloudApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;
@SpringCloudApplication
@EnableEurekaClient
@EnableZuulProxy
public class GatewayApplication {
public static void main(String[] args){
SpringApplication.run(GatewayApplication.class, args);
}
}
依次啟動eureka-server,eureka-client,gateway-service再呼叫
http://localhost:8886/hello?name=match
瀏覽器返回:
hello! match
gitee程式碼地址:https://gitee.com/leftbehindmatches/spring-cloud-examples/tree/master/spring-cloud-gateway