说明: spring cloud + gateway + eureka + 网关过滤器
网关项目和模拟请求项目作为消费者注册到eureka中,另外起了一个eureka注册中心项目
新建eureka注册中心项目:
添加依赖: 注意依赖是eureka-server
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.wm</groupId>
<artifactId>eureka-server</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>eureka-server</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<spring-cloud.version>Hoxton.RC1</spring-cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
<version>2.1.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
</repository>
</repositories>
</project>
在启动类添加注解: @EnableEurekaServer
package com.wm.eurekaserver;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
@SpringBootApplication
@EnableEurekaServer
public class EurekaServerApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaServerApplication.class, args);
}
}
添加配置文件: application.yml
spring:
application:
name: eureka-server
server:
port: 9090
eureka:
instance:
#主机名称
hostname: eureka-server
client:
fetchRegistry: false
registerWithEureka: false #是否将eureka自身作为应用注册到eureka注册中心
serviceUrl:
## eureka注册端口,需要保存一致,和本项目的端口一样
defaultZone: http://localhost:9090/eureka/
eureka注册中心项目就完成了
新建一个controller访问项目,类似业务项目啥的
添加依赖: 注意依赖是: eureka-client
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.wm</groupId>
<artifactId>testgateway</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>testgateway</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
<version>2.1.3.RELEASE</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
启动类添加注解: @EnableDiscoveryClient 或者 @EnableEurekaClient 区别是后者仅在使用eureka时使用,前者在consul作为注册中心也可以生效
package com.wm.testgateway;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@SpringBootApplication
@EnableDiscoveryClient
public class TestgatewayApplication {
public static void main(String[] args) {
SpringApplication.run(TestgatewayApplication.class, args);
}
}
添加application.yml:
spring:
application:
name: test-gateway
eureka:
client:
serviceUrl:
defaultZone: http://localhost:9090/eureka/
server:
port: 8080
新建controller类模拟请求访问:
package com.wm.testgateway.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
/***
* @ClassName: GatewayController
* @Description:
* @Author: wm_yu
* @Create_time: 10:26 2019-11-7
*/
@RestController
public class GatewayController {
@GetMapping("/yu")
public String test(String name){
return String.format("hello,%s",name);
}
}
测试网关(模拟业务项目)完成了
新建网关配置项目:
添加依赖: 注意依赖:eureka-client
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.wm</groupId>
<artifactId>gateway</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>gateway</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<spring-cloud.version>Hoxton.RC1</spring-cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
<version>2.1.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
<version>2.1.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.62</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
</repository>
</repositories>
</project>
启动类配置:
package com.wm.gateway;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@SpringBootApplication
@EnableDiscoveryClient
public class GatewayApplication {
public static void main(String[] args) {
SpringApplication.run(GatewayApplication.class, args);
}
}
新建全局filter类+过滤工厂类:
MyGlobalFilter.java
全局过滤器,不需要再apllication中任何的配置,直接注册到spring就可以生效
package com.wm.gateway.filter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.util.List;
/***
* @ClassName: MyGlobalFilter
* @Description: 自定义gateway全局过滤器,全局过滤器无需配置,对所有的路由都生效
* @Author: wm_yu
* @Create_time: 14:30 2019-11-7
*/
@Slf4j
@Component
public class MyGlobalFilter implements GlobalFilter, Ordered {
private static final String TOKEN = "token";
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
//获取当前请求的url
String requestUrl = exchange.getRequest().getURI().toString();
log.info("请求进入全局过滤器:{}",requestUrl);
//获取到请求头信息,校验是否含有token
HttpHeaders headers = exchange.getRequest().getHeaders();
List<String> tokenList = headers.get(TOKEN);
if(CollectionUtils.isEmpty(tokenList) || StringUtils.isEmpty(tokenList.get(0))){
//设置异常状态值
exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
//截断访问,直接返回异常信息
return exchange.getResponse().setComplete();
}
log.info("请求token:{}",tokenList.get(0));
//TODO 校验token合法性等等,自定义逻辑
//放行请求
return chain.filter(exchange);
}
@Override
public int getOrder() {
return Ordered.LOWEST_PRECEDENCE;
}
}
MyAuthGatewayFilterFactory.java
package com.wm.gateway.filter.factory;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
/***
* @ClassName: MyAuthGatewayFilterFactory
* @Description: 自定义过滤器工厂, 需要以GatewayFilterFactory结尾, 过滤器的名称是前面部分
* @Author: wm_yu
* @Create_time: 15:10 2019-11-7
*/
@Component
@Slf4j
public class MyAuthGatewayFilterFactory extends AbstractGatewayFilterFactory<MyAuthGatewayFilterFactory.Config> {
public MyAuthGatewayFilterFactory() {
super(Config.class);
}
@Override
public GatewayFilter apply(Config config) {
log.info("加载配置类:{}", JSON.toJSONString(config));
return (exchange, chain) -> {
ServerHttpRequest request = exchange.getRequest();
String requestUrl = request.getURI().toString();
log.info("访问请求进入了自定义的过滤工厂:{}",requestUrl);
//读取是否不校验name的参数放行,自定义的参数,true表示需要校验,false为不校验
if (!config.getEnable()) {
return chain.filter(exchange);
}
ServerHttpResponse response = exchange.getResponse();
if(StringUtils.isEmpty(config.getName())){
response.setStatusCode(HttpStatus.UNAUTHORIZED);
return response.setComplete();
}
return chain.filter(exchange);
};
}
public static class Config {
private Boolean isEnable;
private String name;
public Boolean getEnable() {
return isEnable;
}
public void setEnable(Boolean enable) {
isEnable = enable;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
}
这个命名是有规定的, 需要以GatewayFilterFactory结尾,前面部分的就是过滤器的名称,也就是在application.yml的配置名称
需要在appplication.yml进行配置,在filters下进行一些自定义的配置,注意过滤器的名称
完整的配置如下:
server:
port: 9000
yu:
uri: lb://test-gateway
spring:
application:
name: my_gateway
cloud:
gateway:
discovery:
locator:
enabled: true # 开启通过服务中心的自动根据 serviceId 创建路由的功能
routes:
# This route rule used to forward request to activity server
- id: gateway-route
uri: ${yu.uri} # uri以lb://开头(lb代表从注册中心获取服务),后面接的就是你需要转发到的服务名称 ,注意服务名称是服务:项目配置的 spring.application.name
predicates:
- Path=/yu/** # 表示以/yu/**的url会被转发到test-gateway服务去
filters:
- name: MyAuth #定义的过滤器名称 + GatewayFilterFactory就是类名称了
args:
name: wm_yu
enable: false
### 解释: 访问本服务地址: http://localhost:9000/user 转发到服务 test-gateway 地址: http://localhost:8080/user
eureka:
client:
serviceUrl:
defaultZone: http://localhost:9090/eureka/
instance:
prefer-ip-address: true
下面启动项目,先启动eureka-server项目:
可以看到eureka注册中心项目: 注册了两个服务
查看eureka管理ui界面: http://localhost:9090
可以看到网关配置项目:
下面测试:
使用网关项目的端口号: 9000,如下,首先不携带token请求
什么信息都没有,查看控制台日志:
可以看到两个Filter都进入了,且全局过滤器后访问
携带token访问:
成功访问到了,test-gateway项目
查看控制台:
这是直接使用appilication.yml配置的过滤器,还有一种方法是使用代码写入,不推荐,造成硬编码
如果你的配置是 Key、Value 这种形式的,那么可以不用自己定义配置类,直接继承 AbstractNameValueGatewayFilterFactory 类即可。
AbstractNameValueGatewayFilterFactory 类继承了 AbstractGatewayFilterFactory,定义了一个 NameValueConfig 配置类,NameValueConfig 中有 name 和 value 两个字段。
我们可以直接使用,AddRequestHeaderGatewayFilterFactory、AddRequestParameterGatewayFilterFactory 等都是直接继承的 AbstractNameValueGatewayFilterFactory。
参见博客: http://c.biancheng.net/view/5440.html