我们公司用了 6 年的网关服务,动态路由、鉴权、限流等都有,稳的一批!
阅读本文大概需要 6 分钟。
来自:juejin.cn/post/7004756545741258765
前言
搭建服务
框架
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.0.RELEASE</version>
</parent>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-gateway-core</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
路由配置
server:
port: 8080
spring:
cloud:
gateway:
enabled: true
routes:
- id: demo-server
uri: http://localhost:8081
predicates:
- Path=/demo-server/**
filters:
- StripPrefix= 1
解读配置
现在有一个服务demo-server部署在本机,地址和端口为 127.0.0.1:8081
,所以路由配置uri为http://localhost:8081
使用网关服务路由到此服务, predicates -Path=/demo-server/**
,网关服务的端口为8080,启动网关服务,访问localhost:8080/demo-server
,路由断言就会将请求路由到demo-server直接访问demo-server的接口 localhost:8081/api/test
,通过网关的访问地址则为localhost:8080/demo-server/api/test,predicates
配置将请求断言到此路由,filters-StripPrefix=1
代表将地址中/后的第一个截取,所以demo-server就截取掉了
动态路由
Nacos配置
[{
"id": "xxx-server",
"order": 1, #优先级
"predicates": [{ #路由断言
"args": {
"pattern": "/xxx-server/**"
},
"name": "Path"
}],
"filters":[{ #过滤规则
"args": {
"parts": 0 #k8s服务内部访问容器为http://xxx-server/xxx-server的话,配置0即可
},
"name": "StripPrefix" #截取的开始索引
}],
"uri": "http://localhost:8080/xxx-server" #目标地址
}]
比对一下json配置与yaml配置
{
"id":"demo-server",
"predicates":[
{
"args":{
"pattern":"/demo-server/**"
},
"name":"Path"
}
],
"filters":[
{
"args":{
"parts":1
},
"name":"StripPrefix"
}
],
"uri":"http://localhost:8081"
}
spring:
cloud:
gateway:
enabled: true
routes:
- id: demo-server
uri: http://localhost:8081
predicates:
- Path=/demo-server/**
filters:
- StripPrefix= 1
代码实现
@Component
public class NacosDynamicRouteService implements ApplicationEventPublisherAware {
private static final Logger LOGGER = LoggerFactory.getLogger(NacosDynamicRouteService.class);
@Autowired
private RouteDefinitionWriter routeDefinitionWriter;
private ApplicationEventPublisher applicationEventPublisher;
/** 路由id */
private static List<String> routeIds = Lists.newArrayList();
/**
* 监听nacos路由配置,动态改变路由
* @param configInfo
*/
@NacosConfigListener(dataId = "routes", groupId = "gateway-server")
public void routeConfigListener(String configInfo) {
clearRoute();
try {
List<RouteDefinition> gatewayRouteDefinitions = JSON.parseArray(configInfo, RouteDefinition.class);
for (RouteDefinition routeDefinition : gatewayRouteDefinitions) {
addRoute(routeDefinition);
}
publish();
LOGGER.info("Dynamic Routing Publish Success");
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
}
}
/**
* 清空路由
*/
private void clearRoute() {
for (String id : routeIds) {
routeDefinitionWriter.delete(Mono.just(id)).subscribe();
}
routeIds.clear();
}
@Override
public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
this.applicationEventPublisher = applicationEventPublisher;
}
/**
* 添加路由
*
* @param definition
*/
private void addRoute(RouteDefinition definition) {
try {
routeDefinitionWriter.save(Mono.just(definition)).subscribe();
routeIds.add(definition.getId());
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
}
}
/**
* 发布路由、使路由生效
*/
private void publish() {
this.applicationEventPublisher.publishEvent(new RefreshRoutesEvent(this.routeDefinitionWriter));
}
}
过滤器
GlobalFilter filter()
实现过滤器业务Ordered getOrder()
定义过滤器执行顺序
鉴权过滤器
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis-reactive</artifactId>
</dependency>
spring:
redis:
host: redis-server
port: 6379
password:
database: 0
代码实现
定义过滤器AuthFilter 获取请求对象 从请求头或参数或cookie中获取token(支持多种方式传token对于客户端更加友好,比如部分web下载请求会新建一个页面,在请求头中传token处理起来比较麻烦) 没有token,返回401 有token,查询redis是否有效 无效则返回401,有效则完成验证放行 重置token过期时间、添加内部请求头信息方便业务系统权限处理
@Component
public class AuthFilter implements GlobalFilter, Ordered {
@Autowired
private RedisTemplate<String, String> redisTemplate;
private static final String TOKEN_HEADER_KEY = "auth_token";
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
// 1.获取请求对象
ServerHttpRequest request = exchange.getRequest();
// 2.获取token
String token = getToken(request);
ServerHttpResponse response = exchange.getResponse();
if (StringUtils.isBlank(token)) {
// 3.token为空 返回401
response.setStatusCode(HttpStatus.UNAUTHORIZED);
return response.setComplete();
}
// 4.验证token是否有效
String userId = getUserIdByToken(token);
if (StringUtils.isBlank(userId)) {
// 5.token无效 返回401
response.setStatusCode(HttpStatus.UNAUTHORIZED);
return response.setComplete();
}
// token有效,后续业务处理
// 从写请求头,方便业务系统从请求头获取用户id进行权限相关处理
ServerHttpRequest.Builder builder = exchange.getRequest().mutate();
request = builder.header("user_id", userId).build();
// 延长缓存过期时间-token缓存用户如果一直在操作就会一直重置过期
// 这样避免用户操作过程中突然过期影响业务操作及体验,只有用户操作间隔时间大于缓存过期时间才会过期
resetTokenExpirationTime(token, userId);
// 完成验证
return chain.filter(exchange);
}
@Override
public int getOrder() {
// 优先级 越小越优先
return 0;
}
/**
* 从redis中获取用户id
* 在登录操作时候 登陆成功会生成一个token, redis得key为auth_token:token 值为用户id
*
* @param token
* @return
*/
private String getUserIdByToken(String token) {
String redisKey = String.join(":", "auth_token", token);
return redisTemplate.opsForValue().get(redisKey);
}
/**
* 重置token过期时间
*
* @param token
* @param userId
*/
private void resetTokenExpirationTime(String token, String userId) {
String redisKey = String.join(":", "auth_token", token);
redisTemplate.opsForValue().set(redisKey, userId, 2, TimeUnit.HOURS);
}
/**
* 获取token
*
* @param request
* @return
*/
private static String getToken(ServerHttpRequest request) {
HttpHeaders headers = request.getHeaders();
// 从请求头获取token
String token = headers.getFirst(TOKEN_HEADER_KEY);
if (StringUtils.isBlank(token)) {
// 请求头无token则从url获取token
token = request.getQueryParams().getFirst(TOKEN_HEADER_KEY);
}
if (StringUtils.isBlank(token)) {
// 请求头和url都没有token则从cookies获取
HttpCookie cookie = request.getCookies().getFirst(TOKEN_HEADER_KEY);
if (cookie != null) {
token = cookie.getValue();
}
}
return token;
}
}
总结
还在用Xshell?你out了,推荐一个更现代的终端连接工具
请别再使用 SimpleDateFormat 格式化时间了,DateTimeFormatter 更出色!
互联网初中高级大厂面试题(9个G) 内容包含Java基础、JavaWeb、MySQL性能优化、JVM、锁、百万并发、消息队列、高性能缓存、反射、Spring全家桶原理、微服务、Zookeeper......等技术栈!
⬇戳阅读原文领取! 朕已阅
评论