Gateway网关路由以及predicates用法(项目中使用场景)

1.Gateway+nacos整合微服务

服务注册在nacos上,通过Gateway路由网关配置统一路由访问

这里主要通过yml方式说明:

route:

    config:

    #type:database nacos yml

    data-type: yml

    group: DEFAULT_GROUP

    data-id: jeecg-gateway-router

配置路由:

Gateway网关路由以及predicates用法(项目中使用场景)_第1张图片

 

通过断言里Path地址访问到对应的system-service服务,

2.StripPrefix 过滤配置

很多时候也会有这么一种请求,用户请求路径是/smart-web/sys/**,而真实路径是/sys/**,这时候我们需要去掉/smart-web才是真实路径,此时可以使用StripPrefix功能来实现路径的过滤操作,如下配置:

如上,我们访问网关地址http://localhost:9999/smart-web/sys/**时
若无StripPrefix过滤器时,gateway 发送请求到后台服务system-service的url就是http://system-service/smart-web/sys/**
若有StripPrefix过滤器时,gateway会根据StripPrefix=1所配的值(这里是1)去掉URL路径中的部分前缀(这里去掉一个前缀,即去掉/smart-web)
发送请求到后台服务spring-cloud-producer的url变成http://system-service/sys/**

PS:加了/smart-web是为了前端访问路径,不暴露真实的路径

附加:

After只接受一个参数,即DateTime格式时间,客户端访问Gateway接口的时间在After指定之后的时间是允许访问的,否则,当前访问被拦截:

- Path=/api/test/**
- After=2022-08-01T15:59:59Z[Asia/Shanghai]

3.gateWay整合swagger问题

 

MySwaggerResourceProvider:

@Override
public List get() {
    List resources = new ArrayList<>();
    List routeHosts = new ArrayList<>();
    // 获取所有可用的host:serviceId
    routeLocator.getRoutes().filter(route -> route.getUri().getHost() != null)
            .filter(route -> !self.equals(route.getUri().getHost()))
            .subscribe(route -> {
                //update-begin---author:zyf ---date:20220413 for:过滤掉无效路由,避免接口文档报错无法打开
                boolean hasRoute = checkRoute(route.getId());
                if (hasRoute) {
                    routeHosts.add(route.getUri().getHost());
                }
                //update-end---author:zyf ---date:20220413 for:过滤掉无效路由,避免接口文档报错无法打开
            });

    // 记录已经添加过的server,存在同一个应用注册了多个服务在nacos上
    Set dealed = new HashSet<>();
    routeHosts.forEach(instance -> {
        // 拼接url
        String url = "/smart-web/" + instance.toLowerCase() + SWAGGER2URL;
        if ("system-service".equalsIgnoreCase(instance)) {
            url = "/smart-web" + SWAGGER2URL;
        }
        if (!dealed.contains(url)) {
            dealed.add(url);
            log.info(" Gateway add SwaggerResource: {}", url);
            SwaggerResource swaggerResource = new SwaggerResource();
            swaggerResource.setUrl(url);
            swaggerResource.setSwaggerVersion("2.0");
            swaggerResource.setName(instance);
            //Swagger排除不展示的服务
            if (!ArrayUtil.contains(excludeServiceIds, instance)) {
                resources.add(swaggerResource);
            }
        }
    });
    return resources;
}

 

你可能感兴趣的:(微服务,gateway,java,服务器)