Spring gateway 路由 配置在数据库

时间:2024-11-21 15:26:47

##动态路由表结构


  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配置

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实体类

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

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

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;
    }
}