当前位置: 代码网 > it编程>编程语言>Java > SpringCloud GateWay动态路由用法

SpringCloud GateWay动态路由用法

2024年10月31日 Java 我要评论
1.网关为什么需要动态路由?网关的核心功能就是通过配置不同路由策略在配合注册中心访问不同的微服务,而默认是在yaml文件中配置路由策略,而在项目上线后,网关作为所有项目的入口肯定不希望重启,所以动态路

1.网关为什么需要动态路由?

网关的核心功能就是通过配置不同路由策略在配合注册中心访问不同的微服务,而默认是在yaml文件中配置路由策略,而在项目上线后,网关作为所有项目的入口肯定不希望重启,所以动态路由是必须的,我们在增加一个服务,在不希望服务重新启动的前提下能路由到该服务,以及是基于代码实现的网关动态路由

2.动态路由原理

public interface routedefinitionrepository
		extends routedefinitionlocator, routedefinitionwriter {
}

routedefinitionrepository是网关路由的存储接口,routedefinitionlocator 是获取存储中的所有路由,routedefinitionwriter主要操作路由的存储和删除。

public interface routedefinitionlocator {
	flux<routedefinition> getroutedefinitions();

}
public interface routedefinitionwriter {
	mono<void> save(mono<routedefinition> route);
	mono<void> delete(mono<string> routeid);
}

而gateway中routedefinitionrepository接口的默认的实现是inmemoryroutedefinitionrepository,即在内存中存储路由配置,而且在 gatewayautoconfiguration 配置中也激活了inmemoryroutedefinitionrepository这个bean,代码如下。

	@bean
	@conditionalonmissingbean(routedefinitionrepository.class)
	public inmemoryroutedefinitionrepository inmemoryroutedefinitionrepository() {
		return new inmemoryroutedefinitionrepository();
	}
public class inmemoryroutedefinitionrepository implements routedefinitionrepository {

	private final map<string, routedefinition> routes = synchronizedmap(
			new linkedhashmap<string, routedefinition>());

	@override
	public mono<void> save(mono<routedefinition> route) {
		return route.flatmap(r -> {
			routes.put(r.getid(), r);
			return mono.empty();
		});
	}
	@override
	public mono<void> delete(mono<string> routeid) {
		return routeid.flatmap(id -> {
			if (routes.containskey(id)) {
				routes.remove(id);
				return mono.empty();
			}
			return mono.defer(() -> mono.error(
					new notfoundexception("routedefinition not found: " + routeid)));
		});
	}
	@override
	public flux<routedefinition> getroutedefinitions() {
		return flux.fromiterable(routes.values());
	}

}

inmemoryroutedefinitionrepository 中可见存储路由的是一个带同步锁的linkedhashmap,而存储删除都是基于这个map对象操作。

3.动态路由设计以及实现

  • 方案一:知道动态路由的原理以后,我们可以基于redis设计一个inredisroutedefinitionrepository 实现 routedefinitionrepository 接口即可,即网关部署多个也能动态解决路由问题
  • 方案二:可以基于nacos 配置动态修改路由(理论上,待验证)nacos的配置也是可以热加载的。
@slf4j
@configuration("redisroutedefinition")
@allargsconstructor
public class inredisroutedefinitionrepository implements routedefinitionrepository {

    private redistemplate redistemplate;

    @override
    public mono<void> save(mono<routedefinition> route) {

        return route.flatmap(r -> {
            redistemplate.opsforhash().put(dynamicrouterconstants.dynamic_router_key_config, r.getid(), new gson().tojson(r));
            return mono.empty();
        });
    }

    @override
    public mono<void> delete(mono<string> routeid) {
        return routeid.flatmap(id -> {
            object router = redistemplate.opsforhash().get(dynamicrouterconstants.dynamic_router_key_config, id);
            if (!objects.isnull(router)) {
                redistemplate.opsforhash().delete(dynamicrouterconstants.dynamic_router_key_config, id);
                return mono.empty();
            }
            return mono.defer(() -> mono.error(
                new notfoundexception("routedefinition not found: " + routeid)));
        });
    }

    @override
    public flux<routedefinition> getroutedefinitions() {
        list<string> values = redistemplate.opsforhash().values(dynamicrouterconstants.dynamic_router_key_config);
        if (collutil.isnotempty(values)) {
            list<routedefinition> definitions = values.stream()
                .map(s -> new gson().fromjson(s, routedefinition.class))
                .collect(collectors.tolist());
            return flux.fromiterable(definitions);
        } else {
            return flux.fromiterable(new arraylist<>());
        }
    }

}

暂时在网关中提供接口实现路由的动态增加和修改controller

@restcontroller
@requestmapping("/route")
@allargsconstructor
public class routecontroller {

    private dynamicrouteservice dynamicrouteservice;

    @postmapping
    public void saveroutedefinition(@requestbody gatewayroutedefinition routedefinition) {
        dynamicrouteservice.saveroutedefinition(routedefinition);
    }

    @deletemapping("/{id}")
    public void deleteroutedefinition(@pathvariable string id) {
        dynamicrouteservice.deleteroutedefinition(id);
    }

    @putmapping
    public void update(@requestbody gatewayroutedefinition routedefinition) {
        dynamicrouteservice.updateroutedefinition(routedefinition);
    }

    @getmapping
    public ipage<routerconfig> getrouterconfigbypage(routerconfigqueryparams params) {
        return dynamicrouteservice.getrouterconfigbypage(params);
    }

}

路由参数

@data
@allargsconstructor
@noargsconstructor
@accessors(chain = true)
public class gatewayroutedefinition {

    /**
     * 路由的id
     */
    private string id;
    /**
     * 路由断言集合配置
     */

    private list<gatewaypredicatedefinition> predicates;
    /**
     * 路由过滤器集合配置
     */

    private list<gatewayfilterdefinition> filters;
    /**
     * 路由规则转发的目标uri
     */
    private string uri;

    /**
     * 路由执行的顺序
     */
    private int order;
}
@data
public class gatewaypredicatedefinition implements serializable {

    /**
     * 断言对应的name
     */
    private string name;

    /**
     * 配置的断言规则
     */
    private map<string, string> args = new linkedhashmap<>();

}
@data
public class gatewayfilterdefinition implements serializable {

    /**
     * filter name
     */
    private string name;
    /**
     * 对应的路由规则
     */
    private map<string, string> args = new linkedhashmap<>();

}

业务层代码 dynamicrouteservice,最主要的是注入routedefinitionwriter 我们自己的实现类,替换默认的配置

@service
public class dynamicrouteserviceimpl implements dynamicrouteservice {

    @resource(name = "redisroutedefinition")
    private routedefinitionwriter routedefinitionwriter;

    @autowired
    private irouterconfigservice routerconfigservice;

    @autowired
    private objectmapper objectmapper;

    @override
    public void saveroutedefinition(gatewayroutedefinition definition) {
        // 判定当前路由以及路径是否存在
        lambdaquerywrapper<routerconfig> wrapper = wrappers.<routerconfig>lambdaquery()
            .eq(routerconfig::getroutername, definition.getid())
            .eq(routerconfig::getrouterpath, definition.geturi());
        list<routerconfig> list = routerconfigservice.list(wrapper);
        bizverify.verify(collutil.isempty(list), "路由已经存在");
        routerconfigservice.save(paramsconvert(definition));
        routedefinition routerdefinition = dynamicrouteutils.converttoroutedefinition(definition);
        routedefinitionwriter.save(mono.just(routerdefinition)).subscribe();
    }

    @override
    public void updateroutedefinition(gatewayroutedefinition routedefinition) {
        routerconfigservice.updatebyid(paramsconvert(routedefinition));
        routedefinition definition = dynamicrouteutils.converttoroutedefinition(routedefinition);
        deleteroutedefinition(definition.getid());
        routedefinitionwriter.save(mono.just(definition)).subscribe();
    }

    @override
    public void deleteroutedefinition(string routerid) {
        routerconfigservice.removebyid(routerid);
        routedefinitionwriter
            .delete(mono.just(routerid))
            .then(mono.defer(() -> mono.just(responseentity.ok().build())))
            .onerrorresume((t) -> t instanceof notfoundexception, (t) -> mono.just(responseentity.notfound().build()));
    }


    private routerconfig paramsconvert(gatewayroutedefinition routedefinition) {
        string filterjson = null;
        string predicatesjson = null;
        try {
            filterjson = objectmapper.writevalueasstring(routedefinition.getfilters());
            predicatesjson = objectmapper.writevalueasstring(routedefinition.getpredicates());
        } catch (jsonprocessingexception e) {
            e.printstacktrace();
        }
        return new routerconfig()
            .setroutername(routedefinition.getid())
            .setrouterpath(routedefinition.geturi())
            .setrouterorder(routedefinition.getorder())
            .setrouterfilters(filterjson)
            .setrouterpredicates(predicatesjson);
    }

    @override
    public ipage<routerconfig> getrouterconfigbypage(routerconfigqueryparams params) {
        lambdaquerywrapper<routerconfig> wrapper = wrappers.<routerconfig>lambdaquery()
            .like(strutil.isnotempty(params.getroutername()), routerconfig::getroutername, params.getroutername());
        return routerconfigservice.page(new page<>(params.getpagenum(), params.getpagesize()), wrapper);
    }
}

4.网关中聚合swagger由于动态路由引发不展示的问题

聚合swagger聚合核心代码

package com.kill.core.provider;

import cn.hutool.core.collection.collutil;
import cn.hutool.core.util.strutil;
import lombok.allargsconstructor;
import org.springframework.cloud.gateway.route.routedefinitionrepository;
import org.springframework.cloud.gateway.support.nameutils;
import org.springframework.context.annotation.primary;
import org.springframework.stereotype.component;
import springfox.documentation.swagger.web.swaggerresource;
import springfox.documentation.swagger.web.swaggerresourcesprovider;

import java.util.arraylist;
import java.util.list;

/**
 * <pre>
 * +--------+---------+-----------+---------+
 * |                                        |
 * +--------+---------+-----------+---------+
 * </pre>
 *
 * @author wangjian
 * @since 1019/11/01 11:58:32
 */
@component
@primary
@allargsconstructor
public class swaggerresourceprovider implements swaggerresourcesprovider {

    private static final string swagger2url = "/v2/api-docs";

    private routedefinitionrepository repository;

    @override
    public list<swaggerresource> get() {
        list<swaggerresource> resources = new arraylist<>();
        repository.getroutedefinitions().subscribe(
            route -> {
                if (collutil.isnotempty(route.getpredicates())) {
                    route.getpredicates().foreach(
                        predicatedefinition -> {
                            if (collutil.isnotempty(predicatedefinition.getargs())) {
                                if (strutil.isnotempty(predicatedefinition.getargs().get("pattern"))) {
                                    resources.add(
                                        swaggerresource(route.getid(),
                                            predicatedefinition.getargs().get("pattern").replace("/**", swagger2url)));
                                }
                                if (strutil.isnotempty(predicatedefinition.getargs().get(nameutils.generated_name_prefix + "0"))) {
                                    resources.add(
                                        swaggerresource(route.getid(),
                                            predicatedefinition.getargs().get(nameutils.generated_name_prefix + "0").replace("/**", swagger2url)));
                                }
                            }

                        });
                }
            });
        return resources;
    }

    private swaggerresource swaggerresource(string name, string location) {
        swaggerresource swaggerresource = new swaggerresource();
        swaggerresource.setname(name);
        swaggerresource.setlocation(location);
        swaggerresource.setswaggerversion("2.0");
        return swaggerresource;
    }

}

5.测试一下

swagger中目前只有这一个路由,调用路由新增一个

再次刷新swagger,ok 已经看到新的路由了

redis中也已经看到了路由的配置

6.写在最后

不可能所有的代码拿过来就能用,每个人的理解也不尽相同,记录在这里希望能提供一个思路,能解决到自己遇到的问题,而不是希望大家看到后,说拷贝过来的东西都是垃圾,你可以看,如果没有帮助到你我也很遗憾。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com