核心概念:
Route(路由):
路由是构建⽹关的基本模块,它由
ID
,⽬标
URI
,⼀系列的断⾔和过滤器组成,如果断⾔为
true就
匹配该路由。
Predicate(断⾔、谓词):
开发⼈员可以匹配
HTTP
请求中的所有内容(例如请求头或请求参数),如果请求与断⾔相匹配则进
⾏路由。
Filter(过滤):
指的是
Spring
框架中
GatewayFilter
的实例,使⽤过滤器,可以在请求被路由前或者之后对请求
进⾏修改。
⼯作流程:
1:
客户端向
Spring Cloud Gateway
发出请求。然后在
Gateway Handler Mapping
中找到与请求相匹配的路由
2:
将其发送到
Gateway Web Handler
。
3:Handler
再通过指定的过滤器链来将请求发送到我们实际的服务执⾏业务逻辑,然后返回。过滤器之间⽤虚线分开是因为过滤器可能会在发送代理请求之前(“pre”
)或之后(
“post”
)执⾏业务逻辑。
依赖:
<dependencies>
<!-- spring-cloud gateway,底层基于netty -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<!-- 端点监控 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!-- nacos注册中⼼ -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacosdiscovery</artifactId>
</dependency>
</dependencies>
配置文件(动态路由)例子:
server:
#gateway的端⼝
port: 8888
spring:
application:
name: cloud-gateway
cloud:
nacos:
discovery:
server-addr: 127.0.0.1:8848
gateway:
routes:
- id: service-user
uri: lb://service-user
predicates:
- Path=/user/**
谓词工厂:
spring:
cloud:
gateway:
routes:
- id: wfx-jifen
uri: lb://wfx-goods
predicates:
- Path=/goods/detail/100
- After=2022-11-28T15:26:40.626+08:00[Asia/Shanghai]
- Cookie=name,jack
- Header=token
- Host=**.baidu.com,**.taobao.com
- Query=name,tom
- RemoteAddr=192.168.56.10,192.168.56.11
过滤器:
分成了全局和局部过滤器。局部只针对某一路由,全局针对所有路由。
使用内置过滤器:
spring:
cloud:
gateway:
routes:
- id: add_request_header_route
uri: https://example.org
filters:
- AddRequestHeader=Foo, Bar
一般内置过滤器无法满足需求,所以经常使用自定义过滤器。自定义全局过滤器(请求是否带token的例子):
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.util.HashMap;
import java.util.Map;
@Component
public class AuthFilter implements GlobalFilter, Ordered {
@Autowired
private RedisTemplate<String,String> redisTemplate;
//针对所有的路由进⾏过滤
@Override
public Mono<Void> filter(ServerWebExchange exchange,
GatewayFilterChain chain) {
//过滤器的前处理
ServerHttpRequest request = exchange.getRequest();
ServerHttpResponse response = exchange.getResponse();
//获取当前的请求连接
String path = request.getURI().getPath();
if(path.contains("api/ucenter/login")||path.contains("api/ucenter/register")){
return chain.filter(exchange);
}
String token = request.getHeaders().getFirst("token");
if(StringUtils.isEmpty(token)){
Map res = new HashMap(){{
put("msg", "没有登录!!");
}};
return response(response,res);
}else{
String tokenRedis = redisTemplate.opsForValue().get("token");
if(!tokenRedis.equals(token)){
Map res = new HashMap(){{
put("msg", "令牌⽆效!!");
}};
return response(response,res);
}else{
return chain.filter(exchange); //放⾏
}
}
}
private Mono<Void> response(ServerHttpResponse response,Object msg){
response.getHeaders().add("Content-Type",
"application/json;charset=UTF-8");
String resJson = JSON.toJSONString(msg);
DataBuffer dataBuffer =
response.bufferFactory().wrap(resJson.getBytes());
return response.writeWith(Flux.just(dataBuffer));//响应json数据
}
@Override
public int getOrder() {
return 0;
}
}
跨域:
由于
gateway
使⽤的是
webflux
,⽽不是
springmvc
,所以需要先关闭
springmvc
的
cors
,再从gateway
的
filter
⾥边设置
cors
就⾏了。
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
import org.springframework.web.util.pattern.PathPatternParser;
@Configuration
public class CorsConfig {
//处理跨域
@Bean
public CorsWebFilter corsFilter() {
CorsConfiguration config = new CorsConfiguration();
config.addAllowedMethod("*");
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());
source.registerCorsConfiguration("/**", config);
return new CorsWebFilter(source);
}
}