✨ 添加新特性。gateway 动态路由

This commit is contained in:
冷冷 committed 2018-11-02 21:09:49 +08:00
1 parent d31535f0f2
commit 5dc2482a2a
22 files changed
+445 -16

No files matched your search

@@ -66,4 +66,9 @@ public interface CommonConstant {
* 后端工程名
*/
String BACK_END_PROJECT = "pigx";
/**
* 路由存放
*/
String ROUTE_KEY = "gateway_route_key";
}
@@ -22,9 +22,9 @@ package com.pig4cloud.pigx.common.log;
import com.pig4cloud.pigx.admin.api.feign.RemoteLogService;
import com.pig4cloud.pigx.common.log.aspect.SysLogAspect;
import com.pig4cloud.pigx.common.log.event.SysLogListener;
import com.pig4cloud.pigx.common.security.feign.EnablePigxFeignClients;
import lombok.AllArgsConstructor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@@ -35,8 +35,8 @@ import org.springframework.context.annotation.Configuration;
*/
@Configuration
@AllArgsConstructor
@EnablePigxFeignClients
@ConditionalOnWebApplication
@EnableFeignClients({"com.pig4cloud.pigx.admin.api.feign"})
public class LogAutoConfiguration {
private final RemoteLogService remoteLogService;
@@ -59,7 +59,7 @@ public abstract class BaseResourceServerConfigurerAdapter extends ResourceServer
/**
* 提供子类重写
* <p>
* 1. 不重写,默认支持获取雍熙
* 1. 不重写,默认支持获取用户名
* 2. 重写notGetUser,提供性能
* <p>
* see codegen ResourceServerConfigurer
@@ -5,4 +5,4 @@ spring:
driver-class-name: com.mysql.jdbc.Driver
username: root
password: root
url: jdbc:mysql://pigx-mysql:3306/pigx?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false
url: jdbc:mysql://pigx-mysql:3306/pigxx?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false
@@ -13,6 +13,6 @@ spring:
driver-class-name: com.mysql.jdbc.Driver
username: root
password: root
url: jdbc:mysql://pigx-mysql:3306/pigx?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false
url: jdbc:mysql://pigx-mysql:3306/pigxx?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false
resources:
static-locations: classpath:/static/,classpath:/views/
@@ -14,7 +14,7 @@ spring:
driver-class-name: com.mysql.jdbc.Driver
username: root
password: root
url: jdbc:mysql://pigx-mysql:3306/pigx?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false
url: jdbc:mysql://pigx-mysql:3306/pigxx?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false
elasticjob:
# 分布式任务协调依赖zookeeper
zookeeper:
@@ -13,7 +13,7 @@ spring:
driver-class-name: com.mysql.jdbc.Driver
username: root
password: root
url: jdbc:mysql://pigx-mysql:3306/pigx?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowMultiQueries=true
url: jdbc:mysql://pigx-mysql:3306/pigxx?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowMultiQueries=true
# swagger相关配置,覆盖全局配置
swagger:
+6
View File
@@ -59,6 +59,12 @@
<artifactId>pigx-common-core</artifactId>
<version>${pigx.version}</version>
</dependency>
<!--缓存-->
<dependency>
<groupId>com.pig4cloud</groupId>
<artifactId>pigx-common-cache</artifactId>
<version>${pigx.version}</version>
</dependency>
<!--接口文档-->
<dependency>
<groupId>io.springfox</groupId>
@@ -37,7 +37,7 @@ import java.util.List;
@Primary
@AllArgsConstructor
public class SwaggerProvider implements SwaggerResourcesProvider {
public static final String API_URI = "/v2/api-docs";
private static final String API_URI = "/v2/api-docs";
private final RouteLocator routeLocator;
private final GatewayProperties gatewayProperties;
@@ -0,0 +1,66 @@
/*
* Copyright (c) 2018-2025, lengleng All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* Neither the name of the pig4cloud.com developer nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* Author: lengleng (wangiegie@gmail.com)
*/
package com.pig4cloud.pigx.gateway.filter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.HttpHeaders;
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.web.server.ServerWebExchange;
/**
* @author lengleng
* @date 2018/10/30
* <p>
* 自定义basic认证,针对特殊场景使用
*/
@Slf4j
@Component
public class HttpBasicGatewayFilter extends AbstractGatewayFilterFactory {
@Override
public GatewayFilter apply(Object config) {
return (exchange, chain) -> {
if (hasAuth(exchange)) {
return chain.filter(exchange);
} else {
ServerHttpResponse response = exchange.getResponse();
response.setStatusCode(HttpStatus.UNAUTHORIZED);
response.getHeaders().add(HttpHeaders.WWW_AUTHENTICATE, "Basic Realm=\"pigx\"");
return response.setComplete();
}
};
}
/**
* 简单的basic认证
*
* @param exchange 上下文
* @return 是否有权限
*/
private boolean hasAuth(ServerWebExchange exchange) {
ServerHttpRequest request = exchange.getRequest();
String auth = request.getHeaders().getFirst(HttpHeaders.AUTHORIZATION);
log.info("Basic认证信息为:{}", auth);
return true;
}
}
@@ -28,6 +28,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
@@ -89,7 +90,7 @@ public class ValidateCodeGatewayFilter extends AbstractGatewayFilterFactory {
*/
public static String[] extractAndDecodeHeader(ServerHttpRequest request)
throws IOException, CheckedException {
String header = request.getHeaders().getFirst("Authorization");
String header = request.getHeaders().getFirst(HttpHeaders.AUTHORIZATION);
if (header == null || !header.startsWith(BASIC_)) {
throw new CheckedException("请求头中client信息为空");
@@ -0,0 +1,85 @@
/*
* Copyright (c) 2018-2025, lengleng All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* Neither the name of the pig4cloud.com developer nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* Author: lengleng (wangiegie@gmail.com)
*/
package com.pig4cloud.pigx.gateway.support;
import com.pig4cloud.pigx.common.core.util.R;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Mono;
import java.util.Map;
/**
* @author lengleng
* @date 2018/10/31
* <p>
* 动态路由业务端点
*/
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/route")
public class DynamicRouteEndpoint {
private final DynamicRouteHandler dynamicRouteHandler;
/**
* 获取当前定义的路由信息
*
* @return {"id":"RouteDefinition"}
*/
@GetMapping
public Mono<Map<String, RouteDefinition>> routes() {
return dynamicRouteHandler.routes();
}
/**
* 新增路由
*
* @param route 路由定义
* @return
*/
@PostMapping
public Mono<R> save(@RequestBody Mono<RouteDefinition> route) {
return Mono.just(new R(dynamicRouteHandler.addRoute(route)));
}
/**
* 删除路由
*
* @param id 路由定义ID
* @return
*/
@DeleteMapping("/{id}")
public Mono<R> delete(@PathVariable String id) {
return Mono.just(new R(dynamicRouteHandler.deleteRoute(id)));
}
/**
* 修改路由
*
* @param routeDefinition 路由定义
* @return
*/
@PutMapping
public R edit(@RequestBody RouteDefinition routeDefinition) {
return new R();
}
}
@@ -0,0 +1,85 @@
/*
* Copyright (c) 2018-2025, lengleng All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* Neither the name of the pig4cloud.com developer nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* Author: lengleng (wangiegie@gmail.com)
*/
package com.pig4cloud.pigx.gateway.support;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.event.RefreshRoutesEvent;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.cloud.gateway.route.RouteDefinitionLocator;
import org.springframework.cloud.gateway.route.RouteDefinitionWriter;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;
import java.util.Map;
/**
* @author lengleng
* @date 2018/10/31
* <p>
* 动态路由操作类
* see GatewayControllerEndpoint.java
*/
@Slf4j
@Service
public class DynamicRouteHandler implements ApplicationEventPublisherAware {
private final RouteDefinitionWriter routeDefinitionWriter;
private final RouteDefinitionLocator routeDefinitionLocator;
private ApplicationEventPublisher applicationEventPublisher;
public DynamicRouteHandler(RouteDefinitionWriter routeDefinitionWriter
, RouteDefinitionLocator routeDefinitionLocator) {
this.routeDefinitionWriter = routeDefinitionWriter;
this.routeDefinitionLocator = routeDefinitionLocator;
}
/**
* 获取全部路由
* <p>
* RedisRouteDefinitionWriter.java
* PropertiesRouteDefinitionLocator.java
*
* @return
*/
public Mono<Map<String, RouteDefinition>> routes() {
return routeDefinitionLocator.getRouteDefinitions()
.collectMap(RouteDefinition::getId);
}
/**
* 添加路由
*
* @param route 路由定义
* @return
*/
public Mono<Void> addRoute(Mono<RouteDefinition> route) {
this.applicationEventPublisher.publishEvent(new RefreshRoutesEvent(this));
return routeDefinitionWriter.save(route);
}
public Mono<Void> deleteRoute(String id) {
this.applicationEventPublisher.publishEvent(new RefreshRoutesEvent(this));
return routeDefinitionWriter.delete(Mono.just(id));
}
@Override
public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
this.applicationEventPublisher = applicationEventPublisher;
}
}
@@ -0,0 +1,75 @@
/*
* Copyright (c) 2018-2025, lengleng All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* Neither the name of the pig4cloud.com developer nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* Author: lengleng (wangiegie@gmail.com)
*/
package com.pig4cloud.pigx.gateway.support;
import com.pig4cloud.pigx.common.core.constant.CommonConstant;
import com.pig4cloud.pigx.gateway.support.vo.RouteDefinitionVo;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.boot.web.context.WebServerInitializedEvent;
import org.springframework.cloud.gateway.config.GatewayProperties;
import org.springframework.cloud.gateway.config.PropertiesRouteDefinitionLocator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.EventListener;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.scheduling.annotation.Async;
/**
* @author lengleng
* @date 2018/10/31
* <p>
* 容器启动后保存配置文件里面的路由信息到Redis
*/
@Slf4j
@Configuration
@AllArgsConstructor
public class DynamicRouteInitRunner {
private final RedisTemplate redisTemplate;
private final GatewayProperties gatewayProperties;
@Async
@Order
@EventListener(WebServerInitializedEvent.class)
public void initRoute() {
Boolean result = redisTemplate.delete(CommonConstant.ROUTE_KEY);
log.info("初始化网关路由 {} ", result);
gatewayProperties.getRoutes().forEach(route -> {
RouteDefinitionVo vo = new RouteDefinitionVo();
BeanUtils.copyProperties(route, vo);
log.info("加载路由ID:{},{}", route.getId(), vo);
redisTemplate.setHashValueSerializer(new Jackson2JsonRedisSerializer<>(RouteDefinitionVo.class));
redisTemplate.opsForHash().put(CommonConstant.ROUTE_KEY, route.getId(), vo);
});
log.debug("初始化网关路由结束 ");
}
/**
* 配置文件设置为空redis 加载的为准
*
* @return
*/
@Bean
public PropertiesRouteDefinitionLocator propertiesRouteDefinitionLocator() {
return new PropertiesRouteDefinitionLocator(new GatewayProperties());
}
}
@@ -0,0 +1,80 @@
/*
* Copyright (c) 2018-2025, lengleng All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* Neither the name of the pig4cloud.com developer nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* Author: lengleng (wangiegie@gmail.com)
*/
package com.pig4cloud.pigx.gateway.support;
import com.pig4cloud.pigx.common.core.constant.CommonConstant;
import com.pig4cloud.pigx.gateway.support.vo.RouteDefinitionVo;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.cloud.gateway.route.RouteDefinitionRepository;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.util.ArrayList;
import java.util.List;
/**
* @author lengleng
* @date 2018/10/31
* <p>
* redis 保存路由信息,优先级比配置文件高
*/
@Slf4j
@Component
@AllArgsConstructor
public class RedisRouteDefinitionWriter implements RouteDefinitionRepository {
private final RedisTemplate redisTemplate;
@Override
public Mono<Void> save(Mono<RouteDefinition> route) {
return route.flatMap(r -> {
RouteDefinitionVo vo = new RouteDefinitionVo();
BeanUtils.copyProperties(r, vo);
log.info("保存路由信息{}", vo);
redisTemplate.opsForHash().put(CommonConstant.ROUTE_KEY, r.getId(), vo);
return Mono.empty();
});
}
@Override
public Mono<Void> delete(Mono<String> routeId) {
routeId.subscribe(id -> {
log.info("删除路由信息{}", id);
redisTemplate.opsForHash().delete(CommonConstant.ROUTE_KEY, id);
});
return Mono.empty();
}
@Override
public Flux<RouteDefinition> getRouteDefinitions() {
List<RouteDefinitionVo> values = redisTemplate.opsForHash().values(CommonConstant.ROUTE_KEY);
List<RouteDefinition> definitionList = new ArrayList<>();
values.forEach(vo -> {
RouteDefinition routeDefinition = new RouteDefinition();
BeanUtils.copyProperties(vo, routeDefinition);
definitionList.add(vo);
});
log.debug("redis 中路由定义条数: {}, {}", definitionList.size(), definitionList);
return Flux.fromIterable(definitionList);
}
}
@@ -0,0 +1,32 @@
/*
* Copyright (c) 2018-2025, lengleng All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* Neither the name of the pig4cloud.com developer nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* Author: lengleng (wangiegie@gmail.com)
*/
package com.pig4cloud.pigx.gateway.support.vo;
import org.springframework.cloud.gateway.route.RouteDefinition;
import java.io.Serializable;
/**
* @author lengleng
* @date 2018/10/31
* <p>
* 扩展此类支持序列化a
* See RouteDefinition.class
*/
public class RouteDefinitionVo extends RouteDefinition implements Serializable {
}
@@ -22,7 +22,6 @@ package com.pig4cloud.pigx.admin;
import com.pig4cloud.pigx.common.security.feign.EnablePigxFeignClients;
import com.pig4cloud.pigx.common.swagger.annotation.EnablePigxSwagger2;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.boot.SpringApplication;
import org.springframework.cloud.client.SpringCloudApplication;
@@ -20,13 +20,11 @@
package com.pig4cloud.pigx.admin.config;
import com.pig4cloud.pigx.common.security.component.BaseResourceServerConfigurerAdapter;
import com.pig4cloud.pigx.common.security.filter.TenantIdTtlFilter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.web.access.channel.ChannelProcessingFilter;
/**
* @author lengleng
@@ -23,7 +23,6 @@ package com.pig4cloud.pigx.admin.service;
import com.baomidou.mybatisplus.service.IService;
import com.pig4cloud.pigx.admin.api.entity.SysMenu;
import com.pig4cloud.pigx.admin.api.vo.MenuVO;
import io.swagger.models.auth.In;
import java.util.List;
@@ -20,7 +20,6 @@ package com.pig4cloud.pigx.act.dto;
import lombok.Data;
import java.util.Date;
import java.util.List;
/**
* @author lengleng
@@ -1,7 +1,7 @@
package com.pig4cloud.pigx.act.mapper;
import com.pig4cloud.pigx.act.entity.LeaveBill;
import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.pig4cloud.pigx.act.entity.LeaveBill;
import org.apache.ibatis.annotations.Mapper;
/**
@@ -20,7 +20,6 @@ package com.pig4cloud.pigx.act.service;
import com.baomidou.mybatisplus.plugins.Page;
import org.activiti.engine.repository.Model;
import java.util.List;
import java.util.Map;
/**