基于网关链+数据库构建网关异变链

网关链模型

基于网关链+数据库构建网关异变链_第1张图片

网关异变链模型

基于网关链+数据库构建网关异变链_第2张图片

实现

依赖
application.yml
pom.xml
SpringUtils

创建表

CREATE TABLE `t_gateway_chain` (
  `id` int(12) NOT NULL,
  `bean_name` varchar(16) DEFAULT NULL COMMENT 'bean作用',
  `bean_id` varchar(16) DEFAULT NULL COMMENT 'beanId',
  `grade` int(3) DEFAULT NULL COMMENT '级别',
  `is_open` char(1) DEFAULT NULL COMMENT '是否开启 1是 0否',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=gbk;
insert into t_gateway_chain values(1,"Api接口限流","limitHandler",1,0);
insert into t_gateway_chain values(2,"黑白名单","blackHandler",2,1);

基于网关链+数据库构建网关异变链_第3张图片
GatewayEntity

@Data
public class GatewayEntity {
   /** 主键ID */
   private Integer id;
   /** handler名称 */
   private String beanName;
   /** handler主键id */
   private String beanId;
}

GatewayMapper

@Mapper
public interface GatewayMapper {

    /**
     * 获取所有链节点
     */
    @Select("select id, bean_id as beanId,bean_name as beanName from t_gateway_chain where is_open=1 order by grade asc ")
    public List getChain();
}

ChainHandler

public interface ChainHandler {
    void service();
}

BlackHandler

@Component
public class BlackHandler implements ChainHandler {
    @Override
    public void service() {
        System.out.println(">>>>>>>>>处理黑名单");
    }
}

LimitHandler

@Component
public class LimitHandler implements ChainHandler {
    @Override
    public void service() {
        System.out.println(">>>>>>>>>限流 !");
    }
}

BaseGateWay

@Service
public class BaseGateWay implements ChainHandler {
    @Autowired
    private GatewayMapper gatewayMapper;
    @Autowired
    private SpringUtils springUtils;

    /**
     * service调用此方法即可实现责任链的处理
     */
    @Override
    public void service() {
        List chain = gatewayMapper.getChain();
        if (chain.size() > 0) {
            for (GatewayEntity gatewayEntity : chain) {
                ChainHandler chainHandler = null;
                try {
                    chainHandler = (ChainHandler) springUtils.getBean(gatewayEntity.getBeanId());
                } catch (Exception e) {
                    System.out.println("查看数据库beanId是否配置正确");
                }
                chainHandler.service();
            }
        }else{
        System.out.println("查看数据库是否有开启的链节点(is_open=1)");
    	}
    }
}

GateWayController

@RestController
public class GateWayController {
    @Autowired
    private BaseGateWay baseGateWay;

    @RequestMapping(value = "/gateway")
    public String gateway() {
        baseGateWay.service();
        return "success";
    }
}

App

@SpringBootApplication
public class App {
    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }
}

测试
http://localhost:8088/gateway

在这里插入图片描述
测试结果
基于网关链+数据库构建网关异变链_第4张图片

<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>在这里插入图片描述测试结果基于网关链+数据库构建网关异变链_第5张图片

你可能感兴趣的:(设计模式系列)