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;
    }
}
相关推荐
J_liaty1 小时前
Spring Boot 邮件发送完整指南:带附件、内嵌图片与中文乱码根治方案
java·spring boot·spring·email
sheji70091 小时前
Springboot家教平台中心系统53754--(程序+源码+数据库+调试部署+开发环境)
java·数据库·spring boot·后端·spring·旅游
小宋10211 小时前
Java 数据库访问 vs Python 数据库访问:JDBC vs ORM
java·数据库·python
少云清2 小时前
【安全测试】6_数据库安全性测试 _数据备份、加密、审计、认证
数据库·安全性测试
kyle~2 小时前
Redis(Remote Dictionary Server)
数据库·redis·缓存
砚边数影2 小时前
架构实战:如何利用融合数据库破解用户画像系统的存储瓶颈?
数据库·mongodb·架构·kingbase·数据库平替用金仓·金仓数据库
不剪发的Tony老师2 小时前
FlySpeed:一款通用的SQL查询工具
数据库·sql
攻城狮7号2 小时前
物联网时代2026年时序数据库选型指南
数据库·物联网·时序数据库·apache iotdb
+VX:Fegn08952 小时前
计算机毕业设计|基于springboot + vue动漫交流与推荐平台系统(源码+数据库+文档)
数据库·vue.js·spring boot·后端·课程设计
云姜.2 小时前
如何在idea上使用数据库
java·数据库·intellij-idea