Spring gateway 路由 配置在数据库

##动态路由表结构

java 复制代码
  CREATE TABLE t_server_route(
  id INT PRIMARY KEY,
  route_info VARCHAR(4096),
  route_status INT,
  route_type INT,
  create_time DATETIME,
  update_time DATETIME
  )

##spring gateway yaml配置

java 复制代码
spring:
  application:
    name: public-gateway
#  cloud:
#    gateway:
#      routes:
#        - id: mybatis-plus-test # 路由的唯一标识
#          uri: http://192.168.3.188:9898 # 目标服务的地址
#          predicates:
#            - Path=/test/** # 匹配以 /user/ 开头的请求路径
#          filters:
#            - AddRequestHeader=X-Request-Example, Example # 添加一个请求头
#            - AddRequestParameter=param1, value1 # 添加一个请求参数
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource # 指定Druid连接池
    dynamic:
      primary: master # 设置主数据源的名称
      datasource:
        master:
          url: jdbc:mysql://192.168.3.161:3306/yymdb?useUnicode=true&characterEncoding=utf8&autoReconnect=true&rewriteBatchedStatements=TRUE
          username: yym
          password: 123456
          driver-class-name: com.mysql.jdbc.Driver
      druid:
        max-active: 1
        min-idle: 1
        max-evictable-idle-time-millis: 120000
        max-wait: 1200000
        initial-size: 1
        min-evictable-idle-time-millis: 90000
server:
  port: 8180
# MyBatis-Plus配置
mybatis-plus:
  mapper-locations: classpath:/mapper/*.xml # MyBatis Mapper XML文件的位置
  type-aliases-package: com.yym.entity # 实体类所在的包
  configuration:
    default-statement-timeout: 8
logging:
  config: classpath:config/logback-spring.xml
netty:
  noUnsafe: false

##spring gateway ServerRoute实体类

java 复制代码
import java.util.Date;

public class ServerRoute {

    private Integer id;
    private String routeInfo;
    private Integer routeStatus;
    private Integer route_type;
    private Date createTime;
    private Date updateTime;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getRouteInfo() {
        return routeInfo;
    }

    public void setRouteInfo(String routeInfo) {
        this.routeInfo = routeInfo;
    }

    public Integer getRouteStatus() {
        return routeStatus;
    }

    public void setRouteStatus(Integer routeStatus) {
        this.routeStatus = routeStatus;
    }

    public Integer getRoute_type() {
        return route_type;
    }

    public void setRoute_type(Integer route_type) {
        this.route_type = route_type;
    }

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    public Date getUpdateTime() {
        return updateTime;
    }

    public void setUpdateTime(Date updateTime) {
        this.updateTime = updateTime;
    }
}

##spring gateway 查询动态路由mapper

java 复制代码
import com.yym.entity.ServerRoute;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

import java.util.List;

/**
 * CREATE TABLE t_server_route(
 * id INT PRIMARY KEY,
 * route_info VARCHAR(4096),
 * route_status INT,
 * route_type INT,
 * create_time DATETIME,
 * update_time DATETIME
 * )
 *
 * SELECT * FROM t_server_route
 * */
@Mapper
public interface ServerRouteMapper {

    @Select("select id,route_info,route_status,route_type from t_server_route")
    public List<ServerRoute> getServerRoute();

}

##Spring gateway 动态路由Service

java 复制代码
import com.alibaba.fastjson.JSONObject;
import com.yym.dao.ServerRouteMapper;
import com.yym.entity.ServerRoute;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.cloud.gateway.event.RefreshRoutesEvent;
import org.springframework.cloud.gateway.filter.FilterDefinition;
import org.springframework.cloud.gateway.handler.predicate.PredicateDefinition;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.cloud.gateway.route.RouteDefinitionWriter;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Service
public class DynamicRoutesService implements ApplicationEventPublisherAware, ApplicationRunner, ApplicationContextAware {

    @Autowired
    private RouteLocator routeLocator;

    private ServerRouteMapper serverRouteMapper;

    @Autowired
    private RouteDefinitionWriter routeDefinitionWriter;

    private ApplicationContext applicationContext;

    private ApplicationEventPublisher publisher;

    private void loadDynamicRoutes() {
        serverRouteMapper = applicationContext.getBean(ServerRouteMapper.class);
        List<ServerRoute> serverRoutes = serverRouteMapper.getServerRoute();
        for(ServerRoute serverRoute:serverRoutes) {
            routeDefinitionWriter.save(Mono.just(createRoute(serverRoute))).subscribe();
        }
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        loadDynamicRoutes();
        publisher.publishEvent(new RefreshRoutesEvent(this));
    }

    public RouteDefinition createRoute(ServerRoute serverRoute) {
        JSONObject routeJSONObject = JSONObject.parseObject(serverRoute.getRouteInfo());
        RouteDefinition routeDefinitionDB = JSONObject.parseObject(serverRoute.getRouteInfo(),RouteDefinition.class);
        return routeDefinitionDB;
    }

    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
        this.publisher = applicationEventPublisher;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
相关推荐
微学AI41 分钟前
国产数据库替代MongoDB的技术实践过程:金仓多模数据库在电子证照系统中的深度应用
数据库·人工智能·1024程序员节
TDengine (老段)1 小时前
TDengine 数据函数 ROUND 用户手册
java·大数据·数据库·物联网·时序数据库·tdengine·1024程序员节
TDengine (老段)1 小时前
TDengine 数学函数 RAND 用户手册
java·大数据·数据库·物联网·时序数据库·tdengine·涛思数据
JH30731 小时前
jvm,tomcat,spring的bean容器,三者的关系
jvm·spring·tomcat
野犬寒鸦1 小时前
从零起步学习MySQL || 第十章:深入了解B+树及B+树的性能优势(结合底层数据结构与数据库设计深度解析)
java·数据库·后端·mysql·1024程序员节
GZ_TOGOGO1 小时前
Oracle OCP考试报名常见问题详解
数据库·oracle·ocp认证
睡不醒的猪儿1 小时前
nginx日志同步阿里云datahub后写入数据库
数据库·nginx·阿里云
xie_zhr1 小时前
【PB案例学习笔记】-46在数据窗口中编辑数据
数据库·his·1024程序员节·干货分享·pb·powerbuilder
小小的木头人2 小时前
Redis 集群安装指南
数据库·redis
星空的资源小屋2 小时前
Antares SQL,一款跨平台开源 SQL 客户端
数据库·人工智能·pdf·开源·电脑·excel·1024程序员节