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;
    }
}
相关推荐
NiNg_1_2345 分钟前
Python中Tushare(金融数据库)入门详解
数据库·python·金融
2401_857610031 小时前
实验室管理现代化:Spring Boot技术方案
数据库·spring boot·后端
荆州克莱1 小时前
Redis | Redis常用命令及示例总结(API)
spring boot·spring·spring cloud·css3·技术
微微一笑吓死谁1 小时前
linux系统中oracle数据库数据泵导入dmp数据
linux·数据库·oracle
天草二十六_简村人1 小时前
Java语言编程,通过阿里云mongo数据库监控实现数据库的连接池优化
java·jvm·数据库·mongodb·阿里云·微服务·云计算
长风清留扬2 小时前
图文解说:MySQL核心模块知识和流程
大数据·数据库·mysql·面试
RainbowSea2 小时前
5. Spring Cloud OpenFeign 声明式 WebService 客户端的超详细使用
java·spring·spring cloud
听潮阁2 小时前
【SpringCloud详细教程】-02-微服务环境搭建
spring·spring cloud·微服务
highfish9202 小时前
Django实现智能问答助手-数据库方式读取问题和答案
数据库·python·django
blammmp3 小时前
MySQL:视图
数据库·mysql