Sprint Cloud Gateway 动态路由

版本:2.1.0

Controller

@RestController
@RequestMapping("/route")
public class RouteConfigController {
    private Logger log = LoggerFactory.getLogger(RouteConfigController.class);

    @Autowired
    private RouteConfigService routeService;

    /**
     * 获取当前的路由列表
     * @return
     */
    @GetMapping("/list")
    public Mono<List<Map<String, Object>>> routes() {
        return routeService.routes();
    }

    /**
     * 添加路由
     * @param definition
     * @return
     */
    @PostMapping("/add")
    public String add(@RequestBody RouteDefinition definition) {
        try {
            return routeService.add(definition);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("error happened {}:", e);
            return "添加路由异常" + e;
        }
    }

    /**
     * 删除路由
     * @param id
     * @return
     */
    @DeleteMapping("/delete/{id}")
    public Mono<ResponseEntity<Object>> delete(@PathVariable String id) {
        return routeService.delete(id);
    }

    /**
     * 更新路由
     * @param definition
     * @return
     */
    @PostMapping("/update")
    public String update(@RequestBody RouteDefinition definition) {
        return routeService.update(definition);
    }

}

RouteConfigService

RouteConfigServiceImpl实现RouteConfigService, ApplicationEventPublisherAware后可以对Route进行get和set操作,也可以自由发挥定义规则。

@Service
public class RouteConfigServiceImpl implements RouteConfigService, ApplicationEventPublisherAware {

    private Logger log = LoggerFactory.getLogger(RouteConfigServiceImpl.class);

    @Autowired
    private RouteDefinitionWriter routeDefinitionWriter;

    @Autowired
    private RouteDefinitionLocator routeDefinitionLocator;
    @Autowired
    private RouteLocator routeLocator;
    private ApplicationEventPublisher publisher;

    /**
     * 获取路由列表
     * @return
     */
    @Override
    public Mono<List<Map<String, Object>>> routes() {
        Mono<Map<String, RouteDefinition>> routeDefs = this.routeDefinitionLocator
                .getRouteDefinitions().collectMap(RouteDefinition::getId);
        Mono<List<Route>> routes = this.routeLocator.getRoutes().collectList();
        return Mono.zip(routeDefs, routes).map(tuple -> {
            Map<String, RouteDefinition> defs = tuple.getT1();
            List<Route> routeList = tuple.getT2();
            List<Map<String, Object>> allRoutes = new ArrayList<>();

            routeList.forEach(route -> {
                HashMap<String, Object> r = new HashMap<>();
                r.put("route_id", route.getId());
                r.put("order", route.getOrder());
                if (defs.containsKey(route.getId())) {
                    r.put("route_definition", defs.get(route.getId()));
                }
                else {
                    HashMap<String, Object> obj = new HashMap<>(16);
                    obj.put("predicate", route.getPredicate().toString());
                    if (!route.getFilters().isEmpty()) {
                        ArrayList<String> filters = new ArrayList<>();
                        for (GatewayFilter filter : route.getFilters()) {
                            filters.add(filter.toString());
                        }
                        obj.put("filters", filters);
                    }
                    if (!obj.isEmpty()) {
                        r.put("route_object", obj);
                    }
                }
                allRoutes.add(r);
            });

            return allRoutes;
        });
    }

    /**
     * 增加路由
     * @param definition
     * @return
     */
    @Override
    public String add(RouteDefinition definition) {
        try {
            routeDefinitionWriter.save(Mono.just(definition)).subscribe();
            this.publisher.publishEvent(new RefreshRoutesEvent(this));
            return "success";
        } catch (Exception e){
            return "add route  fail";
        }
    }

    /**
     * 更新路由
     * @param definition
     * @return
     */
    @Override
    public String update(RouteDefinition definition) {
        try {
            this.routeDefinitionWriter.delete(Mono.just(definition.getId()));
        } catch (Exception e) {
            return "update fail,not find route  routeId: "+definition.getId();
        }
        try {
            routeDefinitionWriter.save(Mono.just(definition)).subscribe();
            this.publisher.publishEvent(new RefreshRoutesEvent(this));
            return "success";
        } catch (Exception e) {
            return "update route  fail";
        }
    }

    /**
     * 删除路由
     * @param id
     * @return
     */
    @Override
    public Mono<ResponseEntity<Object>> delete(String id) {
        return this.routeDefinitionWriter.delete(Mono.just(id))
                .then(Mono.defer(() -> Mono.just(ResponseEntity.ok().build())))
                .onErrorResume(t -> t instanceof NotFoundException, t -> Mono.just(ResponseEntity.notFound().build()));
    }

    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
        this.publisher = applicationEventPublisher;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值