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;
    }
}
相关推荐
程序员黄同学1 小时前
如何使用 Python 连接 MySQL 数据库?
数据库·python·mysql
新手小袁_J2 小时前
实现Python将csv数据导入到Neo4j
数据库·python·neo4j·《我是刑警》·python连接neo4j·python导入csv·csv数据集导入neo4j
シ風箏2 小时前
Neo4j【环境部署 02】图形数据库Neo4j在Linux系统ARM架构下的安装使用
linux·数据库·arm·neo4j
张声录13 小时前
【ETCD】【实操篇(四)】etcd常见问题快问快答FAQ
数据库·etcd
CherishTaoTao4 小时前
sqlite基础
数据库·oracle·sqlite
嶔某5 小时前
MySql:基本查询
数据库·mysql
AI人H哥会Java7 小时前
【Spring】Spring的模块架构与生态圈—Spring MVC与Spring WebFlux
java·开发语言·后端·spring·架构
开心工作室_kaic7 小时前
springboot461学生成绩分析和弱项辅助系统设计(论文+源码)_kaic
开发语言·数据库·vue.js·php·apache
小马爱打代码7 小时前
SpringCloud(注册中心+OpenFeign+网关+配置中心+服务保护+分布式事务)
分布式·spring·spring cloud
毕设资源大全7 小时前
基于SpringBoot+html+vue实现的林业产品推荐系统【源码+文档+数据库文件+包部署成功+答疑解惑问到会为止】
java·数据库·vue.js·spring boot·后端·mysql·html