spring-cloud-gateway配置整合Eureka,实现AbstractGatewayFilterFactory编写简单自定义局部过滤器
spring cloud版本:2020.0.3
spring boot版本:2.5.2
导包
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<!--后面用的整合eareka-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
编写配置文件application.yml
server:
port: 9014
spring:
application:
name: tensquare-gateway
cloud:
gateway:
routes:
- id: tensquare-article #可以任意
uri: lb://tensquare-article #lb表示从eareka中找article的ip和端口,如果没有配置eureka的话写url路径htpp://127.0.0.1:1111/article,当访问127.0.0.1:9014/article/时转发到htpp://127.0.0.1:1111/article
# uri: htpp://127.0.0.1:1111/article # 填写具体的服务地址
predicates:
- Path=/article/**
eureka:
client:
service-url:
defaultZone: http://127.0.0.1:6868/eureka/ #注册中心地址
instance:
prefer-ip-address: true #以IP地址注册到服务中心
启动类
@EnableEurekaClient //启用EurekaClient,可不写
@SpringBootApplication
public class GatewayApplication {
public static void main(String[] args) {
SpringApplication.run(GatewayApplication.class, args);
}
}
自定义过滤器
编写自定义过滤器继承AbstractGatewayFilterFactory抽象类
@Component
public class RSAGatewayFilterFactory extends AbstractGatewayFilterFactory {
@Override
public GatewayFilter apply(Object config) {
//返回Gateway对象
return (exchange, chain) -> {
MultiValueMap<String, String> queryParams = exchange.getRequest().getQueryParams();
//获取参数
System.out.println(queryParams.get("a"));
System.out.println("你好");
//获取URI
URI newUri = exchange.getRequest().getURI();
String rawPath = newUri.getRawPath();
System.out.println(rawPath);
rawPath = rawPath + "/2";
//修改URI
ServerHttpRequest build = exchange.getRequest().mutate().path(rawPath).build();
return chain.filter(exchange.mutate().request(build).build());
};
}
}
在配置文件中加入自定义的局部过滤器
spring:
application:
name: tensquare-gateway
cloud:
gateway:
routes:
- id: tensquare-article #可以任意
uri: lb://tensquare-article #lb表示从eareka中找article的ip和端口
predicates:
- Path=/article/**
filters:
- RSA #注意:RSAGatewayFilterFactory,只需要写RSA