欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

基于Nacos实现Spring Cloud Gateway实现动态路由的方法

程序员文章站 2023-11-07 20:09:28
简介该文档主要介绍以nacos为配置中心,实现spring cloud gateway 实现动态路由的功能。spring cloud gateway启动时候,就将路由配置和规则加载到内存里,无法做到不...

简介

该文档主要介绍以nacos为配置中心,实现spring cloud gateway 实现动态路由的功能。spring cloud gateway启动时候,就将路由配置和规则加载到内存里,无法做到不重启网关就可以动态的对应路由的配置和规则进行增加,修改和删除。通过nacos的配置下发的功能可以实现在不重启网关的情况下,实现动态路由。

集成

spring cloud gateway集成

spring-cloud-starter-gateway:路由转发、请求过滤(权限校验、限流以及监控等)

spring-boot-starter-webflux:反应式web框架

spring-boot-starter-actuator:监控系统健康

  <dependency>
			<groupid>org.springframework.cloud</groupid>
			<artifactid>spring-cloud-starter-gateway</artifactid>
		</dependency>
		<dependency>
			<groupid>org.springframework.boot</groupid>
			<artifactid>spring-boot-starter-webflux</artifactid>
		</dependency>

		<dependency>
			<groupid>org.springframework.boot</groupid>
			<artifactid>spring-boot-starter-actuator</artifactid>
		</dependency>

nacos集成

nacos-client:nacos客户端,现在用比较新的版本0.9.0

  <dependency>
			<groupid>com.alibaba.nacos</groupid>
			<artifactid>nacos-client</artifactid>
			<version>0.9.0</version>
		</dependency>

动态路由

dynamicrouteserviceimpl:提供动态路由的基础方法,可通过获取bean操作该类的方法。该类提供新增路由、更新路由、删除路由,然后实现发布的功能。

@service
public class dynamicrouteserviceimpl implements applicationeventpublisheraware {

  @autowired
  private routedefinitionwriter routedefinitionwriter;

  private applicationeventpublisher publisher;


  /**
   * 增加路由
   * @param definition
   * @return
   */
  public string add(routedefinition definition) {
    routedefinitionwriter.save(mono.just(definition)).subscribe();
    this.publisher.publishevent(new refreshroutesevent(this));
    return "success";
  }


  /**
   * 更新路由
   * @param definition
   * @return
   */
  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
   */
  public string delete(string id) {
    try {
      this.routedefinitionwriter.delete(mono.just(id));
      return "delete success";
    } catch (exception e) {
      e.printstacktrace();
      return "delete fail";
    }

  }

  @override
  public void setapplicationeventpublisher(applicationeventpublisher applicationeventpublisher) {
    this.publisher = applicationeventpublisher;
  }

}

routedefinition: 提供路由实体类,主要有predicates匹配来自用户的请求,filters服务路由

@validated
public class routedefinition {
	@notempty
	private string id = uuid.randomuuid().tostring();

	@notempty
	@valid
	private list<predicatedefinition> predicates = new arraylist<>();

	@valid
	private list<filterdefinition> filters = new arraylist<>();

	@notnull
	private uri uri;

	private int order = 0;

	public routedefinition() {}

	public routedefinition(string text) {
		int eqidx = text.indexof("=");
		if (eqidx <= 0) {
			throw new validationexception("unable to parse routedefinition text '" + text + "'" +
					", must be of the form name=value");
		}

		setid(text.substring(0, eqidx));

		string[] args = tokenizetostringarray(text.substring(eqidx+1), ",");

		seturi(uri.create(args[0]));

		for (int i=1; i < args.length; i++) {
			this.predicates.add(new predicatedefinition(args[i]));
		}
	}

	public string getid() {
		return id;
	}

	public void setid(string id) {
		this.id = id;
	}

	public list<predicatedefinition> getpredicates() {
		return predicates;
	}

	public void setpredicates(list<predicatedefinition> predicates) {
		this.predicates = predicates;
	}

	public list<filterdefinition> getfilters() {
		return filters;
	}

	public void setfilters(list<filterdefinition> filters) {
		this.filters = filters;
	}

	public uri geturi() {
		return uri;
	}

	public void seturi(uri uri) {
		this.uri = uri;
	}

	public int getorder() {
		return order;
	}

	public void setorder(int order) {
		this.order = order;
	}

	@override
	public boolean equals(object o) {
		if (this == o) return true;
		if (o == null || getclass() != o.getclass()) return false;
		routedefinition routedefinition = (routedefinition) o;
		return objects.equals(id, routedefinition.id) &&
				objects.equals(predicates, routedefinition.predicates) &&
				objects.equals(order, routedefinition.order) &&
				objects.equals(uri, routedefinition.uri);
	}

	@override
	public int hashcode() {
		return objects.hash(id, predicates, uri);
	}

	@override
	public string tostring() {
		return "routedefinition{" +
				"id='" + id + '\'' +
				", predicates=" + predicates +
				", filters=" + filters +
				", uri=" + uri +
				", order=" + order +
				'}';
	}
}

nacosgatewayproperties:自定义属性绑定值,可通过配置文件配置属性。

@configurationproperties(prefix="nacos", ignoreunknownfields = true)
@configuration
public class nacosgatewayproperties {

	private string address;
	
	private string dataid;
	
	private string groupid;
	
	private long timeout;

	public string getaddress() {
		return address;
	}

	public void setaddress(string address) {
		this.address = address;
	}

	public string getdataid() {
		return dataid;
	}

	public void setdataid(string dataid) {
		this.dataid = dataid;
	}

	public string getgroupid() {
		return groupid;
	}

	public void setgroupid(string groupid) {
		this.groupid = groupid;
	}

	public long gettimeout() {
		return timeout;
	}

	public void settimeout(long timeout) {
		this.timeout = timeout;
	}	
}

dynamicrouteserviceimplbynacos: 实现runner,通过nacos下发动态路由配置

@component
public class dynamicrouteserviceimplbynacos implements commandlinerunner{

	@autowired
  private dynamicrouteserviceimpl dynamicrouteservice;

	@autowired
  private nacosgatewayproperties nacosgatewayproperties;

  /**
   * 监听nacos server下发的动态路由配置
   * @param dataid
   * @param group
   */
  public void dynamicroutebynacoslistener (){
    try {
      configservice configservice=nacosfactory.createconfigservice(nacosgatewayproperties.getaddress());
      string content = configservice.getconfig(nacosgatewayproperties.getdataid(), nacosgatewayproperties.getgroupid(), nacosgatewayproperties.gettimeout());
      system.out.println(content);
      configservice.addlistener(nacosgatewayproperties.getdataid(), nacosgatewayproperties.getgroupid(), new listener() {
        @override
        public void receiveconfiginfo(string configinfo) {
        	list<routedefinition> list = jsonutils.tolist(configinfo, routedefinition.class);
        	list.foreach(definition->{
        		dynamicrouteservice.update(definition);
        	});
        }
        @override
        public executor getexecutor() {
          return null;
        }
      });
    } catch (nacosexception e) {
      e.printstacktrace();
    }
  }

	@override
	public void run(string... args) throws exception {
    dynamicroutebynacoslistener();
		
	}
  
}

nacos配置下发

nacos配置

nacos:
 address: 127.0.0.1:8848
 data-id: dhap-gateway #
 group-id: aaa
 timeout: 5000

nacos属性文件定义

新建dataid为
groupid为aaa

基于Nacos实现Spring Cloud Gateway实现动态路由的方法

[
	{
	"filters": [],
	"id": "blog1",
	"order": 0,
	"predicates": [{
		"args": {
			"pattern": "/z"
		},
		"name": "path"
	}],
	"uri": "https://blog.csdn.net/zhangchangbin123"
},
 {
	"filters": [],
	"id": "blog1",
	"order": 0,
	"predicates": [{
		"args": {
			"pattern": "/c"
		},
		"name": "path"
	}],
	"uri": "https://blog.csdn.net/zhangchangbin123"
}
]

查看路由信息

基于Nacos实现Spring Cloud Gateway实现动态路由的方法

基于Nacos实现Spring Cloud Gateway实现动态路由的方法

基于Nacos实现Spring Cloud Gateway实现动态路由的方法

基于Nacos实现Spring Cloud Gateway实现动态路由的方法

到此这篇关于基于nacos实现spring cloud gateway实现动态路由的方法的文章就介绍到这了,更多相关spring cloud gateway动态路由内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!