spring cloud gateway 网关的代码配置

2020-02-25 16:09:58 浏览数 (1)

在写spring cloud gateway 时,网上查的资料都是把网关的路由配置写在配置文件里,但其实,可以把配置通过代码实现 示例如下:

代码语言:javascript复制
 /**
     * spring:
     * cloud:
     * gateway:
     * routes:
     * - id: nameRoot
     * uri: http://nameservice
     * predicates:
     * - Path=/name/**
     * - Weight=service1, 95
     * filters:
     * - StripPrefix=1
     */

    private void createGatewayRoute(GatewayAppVo gatewayApp) {
        gatewayApp.getMachineList().forEach(gatewayAppMachineVo -> {
            GatewayRouteDto gatewayRouteDto = new GatewayRouteDto();
            gatewayRouteDto.setId(gatewayApp.getId()   "_"   gatewayAppMachineVo.getServerId());
            gatewayRouteDto.setPredicates(createPredicateDefinition(gatewayApp, gatewayAppMachineVo));
            gatewayRouteDto.setFilters(Collections.singletonList(createFilterDefinition()));
            gatewayRouteDto.setUri(gatewayAppMachineVo.getMachineHost());
            gatewayRouteDto.setOrder(gatewayApp.getSequence());
                redisUtils.set(STARMARK_GATEWAY_ROUTES   gatewayApp.getProjectId()   ":"   gatewayApp.getId()   "_"   gatewayAppMachineVo.getServerId(),
                        JSONObject.toJSONString(gatewayRouteDto));

        });
    }

    private List<PredicateDefinition> createPredicateDefinition(GatewayAppVo gatewayAppVo, GatewayAppMachineVo gatewayAppMachineVo) {
        List<PredicateDefinition> predicatesList = new ArrayList<>();
        //增加转发
        {
            Map<String, String> args = new HashMap<>();
            args.put("pattern", "/"   gatewayAppVo.getProjectId()   "/"   gatewayAppVo.getAccessPre());
            args.put("pathPattern", "/"   gatewayAppVo.getProjectId()   "/"   gatewayAppVo.getAccessPre());
            PredicateDefinition predicateDefinition = new PredicateDefinition();
            predicateDefinition.setArgs(args);
            predicateDefinition.setName("Path");
            predicatesList.add(predicateDefinition);
        }
        //增加权重
        if (gatewayAppMachineVo.getWeight() != null) {
            Map<String, String> args = new HashMap<>();
            args.put("weight.group", gatewayAppMachineVo.getServerId());
            args.put("weight.weight", gatewayAppMachineVo.getWeight().toString());
            PredicateDefinition predicateDefinition = new PredicateDefinition();
            predicateDefinition.setArgs(args);
            predicateDefinition.setName("Weight");
            predicatesList.add(predicateDefinition);
        }

        return predicatesList;

    }

    private FilterDefinition createFilterDefinition() {
        Map<String, String> args = new HashMap<>();
        args.put("parts", "1");
        FilterDefinition filterDefinition = new FilterDefinition();
        filterDefinition.setName("StripPrefix");
        filterDefinition.setArgs(args);
        return filterDefinition;

    }

上述代码是我做网关系统里,设置路由的代码,各位可参考!

0 人点赞