目录
  • 配置gateway+nacos动态路由
    • 第一步:首先是设置配置文件的配置列表
    • 第二步:配置监听nacos监听器
    • 第三步:配置nacos的yml文件
  • nacos的智能路由实现与应用
    • 一. 概述
    • 二. 遇到的问题
    • 三. 智能路由的实现
    • 四. 遇到的难点
    • 五. 带来的收益
    • 六. 总结

配置gateway+nacos动态路由

第一步:首先是设置配置文件的配置列表

然后在配置读取配置类上增加刷新注解@refreshscope

import lombok.extern.slf4j.slf4j;
import org.springframework.boot.context.properties.configurationproperties;
import org.springframework.cloud.context.config.annotation.refreshscope;
import org.springframework.cloud.gateway.filter.filterdefinition;
import org.springframework.cloud.gateway.route.routedefinition;
import org.springframework.http.mediatype;
import org.springframework.stereotype.component;
import javax.validation.valid;
import javax.validation.constraints.notnull;
import java.util.arraylist;
import java.util.arrays;
import java.util.list;
/**
 * @author :lhb
 * @date :created in 2020-09-09 08:59
 * @description:gateway路由配置
 * @modified by:
 * @version: $
 */
@slf4j
@refreshscope
@component
@configurationproperties(prefix = "spring.cloud.gateway")
public class gatewayroutes {
    /**
     * 路由列表.
     */
    @notnull
    @valid
    private list<routedefinition> routes = new arraylist<>();
    /**
     * 适用于每条路线的过滤器定义列表
     */
    private list<filterdefinition> defaultfilters = new arraylist<>();
    private list<mediatype> streamingmediatypes = arrays
            .aslist(mediatype.text_event_stream, mediatype.application_stream_json);
    public list<routedefinition> getroutes() {
        return routes;
    }
    public void setroutes(list<routedefinition> routes) {
        this.routes = routes;
        if (routes != null && routes.size() > 0 && log.isdebugenabled()) {
            log.debug("routes supplied from gateway properties: " + routes);
        }
    }
    public list<filterdefinition> getdefaultfilters() {
        return defaultfilters;
    }
    public void setdefaultfilters(list<filterdefinition> defaultfilters) {
        this.defaultfilters = defaultfilters;
    }
    public list<mediatype> getstreamingmediatypes() {
        return streamingmediatypes;
    }
    public void setstreamingmediatypes(list<mediatype> streamingmediatypes) {
        this.streamingmediatypes = streamingmediatypes;
    }
    @override
    public string tostring() {
        return "gatewayproperties{" + "routes=" + routes + ", defaultfilters="
                + defaultfilters + ", streamingmediatypes=" + streamingmediatypes + '}';
    }
}

第二步:配置监听nacos监听器

import cn.hutool.core.exceptions.exceptionutil;
import com.alibaba.fastjson.jsonobject;
import com.alibaba.nacos.api.nacosfactory;
import com.alibaba.nacos.api.propertykeyconst;
import com.alibaba.nacos.api.config.configservice;
import com.alibaba.nacos.api.config.listener.listener;
import com.alibaba.nacos.api.exception.nacosexception;
import lombok.extern.slf4j.slf4j;
import org.apache.commons.collections.collectionutils;
import org.apache.commons.collections.maputils;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.beans.factory.annotation.value;
import org.springframework.cloud.context.scope.refresh.refreshscope;
import org.springframework.cloud.gateway.event.refreshroutesevent;
import org.springframework.cloud.gateway.route.routedefinition;
import org.springframework.cloud.gateway.route.routedefinitionwriter;
import org.springframework.context.applicationeventpublisher;
import org.springframework.context.applicationeventpublisheraware;
import org.springframework.stereotype.component;
import reactor.core.publisher.mono;
import javax.annotation.postconstruct;
import javax.annotation.resource;
import java.util.list;
import java.util.map;
import java.util.properties;
import java.util.set;
import java.util.concurrent.concurrenthashmap;
import java.util.concurrent.executor;
import java.util.concurrent.timeunit;
import java.util.stream.collectors;
/**
 * @author :lhb
 * @date :created in 2020-09-08 16:39
 * @description:监听nacos配置变更
 * @modified by:
 * @version: $
 */
@slf4j
@component
public class gatewaynacosconfiglistener implements applicationeventpublisheraware {
    @autowired
    private routedefinitionwriter routedefinitionwriter;
    private applicationeventpublisher publisher;
    private static final map<string, routedefinition> route_map = new concurrenthashmap<>();
    @autowired
    private gatewayroutes gatewayroutes;
    @resource
    private refreshscope refreshscope;
    @value(value = "${spring.cloud.nacos.config.server-addr}")
    private string serveraddr;
    @value(value = "${spring.cloud.nacos.config.group:default_group}")
    private string group;
    @value(value = "${spring.cloud.nacos.config.namespace}")
    private string namespace;
    private string routedataid = "gateway-routes.yml";
    @postconstruct
    public void onmessage() throws nacosexception {
        log.info("serveraddr={}", serveraddr);
        properties properties = new properties();
        properties.put(propertykeyconst.server_addr, serveraddr);
        properties.put(propertykeyconst.namespace, namespace);
        configservice configservice = nacosfactory.createconfigservice(properties);
        this.publisher(gatewayroutes.getroutes());
        log.info("gatewayproperties=" + jsonobject.tojsonstring(gatewayroutes));
        configservice.addlistener(routedataid, group, new listener() {
            @override
            public executor getexecutor() {
                return null;
            }
            @override
            public void receiveconfiginfo(string config) {
                log.info("监听nacos配置: {}, 旧的配置: {}, 新的配置: {}", routedataid, gatewayroutes, config);
                refreshscope.refresh("gatewayroutes");
                try {
                    timeunit.seconds.sleep(5);
                } catch (interruptedexception e) {
                    log.error(exceptionutil.getmessage(e));
                }
                publisher(gatewayroutes.getroutes());
            }
        });
    }
    private boolean reput(list<routedefinition> routedefinitions) {
        if (maputils.isempty(route_map) && collectionutils.isempty(routedefinitions)) {
            return true;
        }
        if (collectionutils.isempty(routedefinitions)) {
            return true;
        }
        set<string> strings = route_map.keyset();
        return strings.stream().sorted().collect(collectors.joining())
                .equals(routedefinitions.stream().map(v -> v.getid()).sorted().collect(collectors.joining()));
    }
    /**
     * 增加路由
     *
     * @param def
     * @return
     */
    public boolean addroute(routedefinition def) {
        try {
            log.info("添加路由: {} ", def);
            routedefinitionwriter.save(mono.just(def)).subscribe();
            route_map.put(def.getid(), def);
        } catch (exception e) {
            e.printstacktrace();
        }
        return true;
    }
    /**
     * 删除路由
     *
     * @return
     */
    public boolean clearroute() {
        for (string id : route_map.keyset()) {
            routedefinitionwriter.delete(mono.just(id)).subscribe();
        }
        route_map.clear();
        return false;
    }
    /**
     * 发布路由
     */
    private void publisher(string config) {
        this.clearroute();
        try {
            log.info("重新更新动态路由");
            list<routedefinition> gateway = jsonobject.parsearray(config, routedefinition.class);
            for (routedefinition route : gateway) {
                this.addroute(route);
            }
            publisher.publishevent(new refreshroutesevent(this.routedefinitionwriter));
        } catch (exception e) {
            e.printstacktrace();
        }
    }
    /**
     * 发布路由
     */
    private void publisher(list<routedefinition> routedefinitions) {
        this.clearroute();
        try {
            log.info("重新更新动态路由: ");
            for (routedefinition route : routedefinitions) {
                this.addroute(route);
            }
            publisher.publishevent(new refreshroutesevent(this.routedefinitionwriter));
        } catch (exception e) {
            e.printstacktrace();
        }
    }
    @override
    public void setapplicationeventpublisher(applicationeventpublisher app) {
        publisher = app;
    }
}

第三步:配置nacos的yml文件

spring:
  cloud:
    gateway:
      discovery:
        locator:
          enabled: true
          lower-case-service-id: true
      routes:
        # 认证中心
        - id: firefighting-service-user
          uri: lb://firefighting-service-user
          predicates:
            - path=/user/**
          #          - weight=group1, 8
          filters:
            - stripprefix=1
          # 转流服务
        - id: livestream
          uri: http://192.168.1.16:8081
          predicates:
            - path=/livestream/**
          #          - weight=group1, 8
          filters:
            - stripprefix=1
        - id: firefighting-service-directcenter
          uri: lb://firefighting-service-directcenter
          predicates:
            - path=/directcenter/**
          filters:
            - stripprefix=1
        - id: firefighting-service-datainput
          uri: lb://firefighting-service-datainput
          predicates:
            - path=/datainput/**
          filters:
            - stripprefix=1
        - id: firefighting-service-squadron
          uri: lb://firefighting-service-squadron
          predicates:
            - path=/squadron/**
          filters:
            - stripprefix=1
        - id: firefighting-service-iot
          uri: lb://firefighting-service-iot
          predicates:
            - path=/iot/**
          filters:
            - stripprefix=1
        - id: websocket
          uri: lb:ws://firefighting-service-notice
          predicates:
            - path=/notice/socket/**
          filters:
            - stripprefix=1
        - id: firefighting-service-notice
          uri: lb://firefighting-service-notice
          predicates:
            - path=/notice/**
          filters:
            # 验证码处理
            #            - cacherequest
            #            - imgcodefilter
            - stripprefix=1
        - id: websocket
          uri: lb:ws://firefighting-service-notice
          predicates:
            - path=/notice/socket/**
          filters:
            - stripprefix=1
        - id: firefighting-service-supervise
          uri: lb://firefighting-service-supervise
          predicates:
            - path=/supervise/**
          filters:
            - stripprefix=1
        - id: firefighting-service-new-supervise
          uri: lb://firefighting-service-new-supervise
          predicates:
            - path=/new/supervise/**
          filters:
            - stripprefix=2
        - id: firefighting-service-train
          uri: lb://firefighting-service-train
          predicates:
            - path=/train/**
          filters:
            - stripprefix=1
        - id: firefighting-support-user
          uri: lb://firefighting-support-user
          predicates:
            - path=/support/**
          filters:
            - stripprefix=1
        - id: firefighting-service-firesafety
          uri: lb://firefighting-service-firesafety
          predicates:
            - path=/firesafety/**
          filters:
            - stripprefix=1
        - id: firefighting-service-bigdata
          uri: lb://firefighting-service-bigdata
          predicates:
            - path=/bigdata/**
          filters:
            - stripprefix=1
        - id: firefighting-service-act-datainput
          uri: lb://firefighting-service-act-datainput
          predicates:
            - path=/act_datainput/**
          filters:
            - stripprefix=1
        - id: firefighting-service-publicity
          uri: lb://firefighting-service-publicity
          predicates:
            - path=/publicity/**
          filters:
            - stripprefix=1
        - id: firefighting-service-preplan
          uri: lb://firefighting-service-preplan
          predicates:
            - path=/preplan/**
          filters:
            - stripprefix=1
        - id: firefighting-service-uav
          uri: lb://firefighting-service-uav
          predicates:
            - path=/uav/**
          filters:
            - stripprefix=1
        - id: firefighting-service-ard-mgr
          uri: lb://firefighting-service-ard-mgr
          predicates:
            - path=/ard_mgr/**
          filters:
            - stripprefix=1
        - id: admin-server
          uri: lb://admin-server
          predicates:
            - path=/adminsserver/**
          filters:
            - stripprefix=1

nacos的智能路由实现与应用

一. 概述

随着微服务的兴起,我司也逐渐加入了微服务的改造浪潮中。但是,随着微服务体系的发展壮大,越来越多的问题暴露出来。其中,测试环境治理,一直是实施微服务的痛点之一,它的痛主要体现在环境管理困难,应用部署困难,技术方案配合等。最终,基于我司的实际情况,基于注册中心nacos实现的智能路由有效地解决了这个问题。本文主要介绍我司在测试环境治理方面遇到的难题与对应的解决方案。

二. 遇到的问题

1. 困难的环境管理与应用部署

随着公司业务发展,业务逐渐复杂化。这在微服务下带来的一个问题就是服务的不断激增,且增速越来越快。而在这种情况下,不同业务团队如果想并行开发的话,都需要一个环境。假设一套完整环境需要部署1k个服务,那么n个团队就需要部署n*1k个服务,这显然是不能接受的。

2. 缺失的技术方案

从上面的分析可以看出,一个环境部署全量的服务显然是灾难性的。那么就需要有一种技术方案,来解决应用部署的难题。最直接的一个想法就是,每个环境只部署修改的服务,然后通过某种方式,实现该环境的正常使用。当然,这也是我们最终的解决方案。下面会做一个介绍。

3. 研发问题

除了这两个大的问题,还有一些其他的问题也急需解决。包括后端多版本并行联调和前后端联调的难题。下面以实际的例子来说明这两个问题。

<1> 后端多版本并行联调难

某一个微服务,有多个版本并行开发时,后端联调时调用容易错乱。例如这个例子,1.1版本的服务a需要调用1.1版本的服务b,但实际上能调用到吗???

目前使用的配置注册中心是nacos,nacos自身有一套自己的服务发现体系,但这是基于namespace和group的同频服务发现,对于跨namespace的服务,它就不管用了。

<2> 前后端联调难

前端和后端的联调困难,这个问题也是经常遇到的。主要体现在,后端联调往往需要启动多个微服务(因为服务的依赖性)。而前端要对应到某一个后端,也需要特殊配置(比如指定ip等)。下面这个例子,后端人员开发服务a,但却要启动4个服务才能联调。因为服务a依赖于服务b,c,d。

4. 其他问题

除了以上的问题外,还有一些小的问题也可以关注下:

<1> 测试环境排查问题

这个问题不算棘手,登录服务器查看日志即可。但是能否再灵活点,比如让开发人员debug或者在本地调试问题呢?

<2> 本地开发

本地开发,后端往往也依赖多个服务,能不能只启动待开发的服务,而不启动其他旁路服务呢?

三. 智能路由的实现

基于这些需求,智能路由应运而生。它正是为了解决这个问题。最终,我们通过它解决了测试环境治理的难题。

智能路由,能根据不同环境,不同用户,甚至不同机器进行精确路由。下面以一个例子说明。

三个团队,team1,team2和team3各负责不同的业务需求。其中team1只需要改动a服务,team2只需要改动b服务,team3需要在qa环境上验证。通过智能路由,team1,team2只在自己的环境上部署了增量应用,然后在访问该环境的时候,当找不到对应环境的服务时,就从基准环境上访问。而team3只做qa,因此直接访问基准环境即可。可以看到,基准环境上部署了全量服务,除此之外,其他小环境都是增量服务。

下面介绍智能路由的具体实现方案。

1. 原理

通过上图,可以看到,智能路由其实就是流量染色加上服务发现

流量染色:将不同团队的流量进行染色,然后透传到整个链路中。

服务发现:注册中心提供正确的服务发现,当在本环境发现不到待调用的服务时,自动访问基准环境的服务。

通过流量染色,区分出哪些流量是哪些团队的,从而在服务发现时,能正确调用到正确的服务。

另外,我司使用的注册中心是nacos,因此本文将主要介绍基于nacos的智能路由实现,其他注册中心同理,做相应改造即可。

2. 具体实现 <1> 流量染色

智能路由的第一步,就是要做流量的染色,将流量能够沿着链路一直透传下去。那么就需要找到流量的入口,然后在入口处进行染色。下图是网站的内部调用情况,可以看到,流量从nginx进来,最终打到服务集群,因此需要对nginx进行染色。

流量染色主要是在流量的头部加上一些标记,以便识别。这里利用了nginx的proxy_set_header,我们通过下列方式来设置头部。

## nginx的匹配规则设置header
proxy_set_header req_context  "{'version': '1.0'}"

这样子,我们就为版本是1.0的流量设置了头部,其中的参数可以任意添加,这里仅列举最重要的一个参数。

另外,还有一个问题,流量只有从nginx进来,才会带上这个头部。如果是在内部直接访问某个中间的服务,那么这个时候流量是没有头部的。对此,我们的解决方案是filter,通过filter可以动态地拦截请求,修改请求头部,为其初始化一个默认值。

public class flowdyefilter implements filter { 
    @override
    public void dofilter(servletrequest servletrequest, servletresponse servletresponse, filterchain filterchain) throws ioexception, servletexception {
        //1. 获取servletrequest
        httpservletrequest request = (httpservletrequest)servletrequest;
        //2. 获取请求头部
        string context = request.getheader(contextutil.request_context);
        //3. 初始化请求上下文,如果没有,就进行初始化
        initcontext(context);
        try {
            filterchain.dofilter(servletrequest, servletresponse);
        } finally {
            contextutil.clear();
        }
    }
 
    public void initcontext(string contextstr) {
        //json转object
        context context = jsonobject.parseobject(contextstr, globalcontext.class);
        //避免假初始化
        if (context == null) {
            context  = new context();
        }
        //这里进行初始化,如果没值,设置一个默认值
        if (stringutils.isempty(context.getversion())) {
            context.setversion("master");
        }
        ...
        //存储到上下文中
        contextutil.setcurrentcontext(context);
    } 
}
 

通过这个filter,保证了在中间环节访问时,流量仍然被染色。

<2> 流量透传

流量在入口被染色后,需要透传到整个链路,因此需要对服务做一些处理,下面分几种情形分别处理。

1~ spring cloud gateway

对于gateway,保证请求在转发过程中的header不丢,这个是必要的。这里通过gateway自带的globalfilter来实现,代码如下:

public class webfluxflowdyefilter implements globalfilter, ordered { 
    @override
    public mono<void> filter(serverwebexchange exchange, gatewayfilterchain chain) {
        //1. 获取请求上下文
        string context = exchange.getrequest().getheaders().getfirst(contextutil.request_context);
        //2. 构造serverhttprequest
        serverhttprequest serverhttprequest = exchange.getrequest().mutate().header(contextutil.request_context, context).build();
        //3. 构造serverwebexchange
        serverwebexchange serverwebexchange = exchange.mutate().request(serverhttprequest).build();
        return chain.filter(serverwebexchange).then(
            mono.fromrunnable( () -> {
                contextutil.clear();
            })
        );
    } 
}

2~ springcloud:feign

这一类也是最常用的,sc的服务集群都通过feign进行交互,因此只需要配置feign透传即可。在这里,我们利用了feign自带的requestinterceptor,实现请求拦截。代码如下:

@configuration
public class feignautoconfiguration { 
    @bean
    public requestinterceptor headerinterceptor() {
        return requesttemplate -> {
            setrequestcontext(requesttemplate);
        };
    }
 
    private void setrequestcontext(requesttemplate requesttemplate) {
        context context = contextutil.getcurrentcontext();
        if (context != null) {
            requesttemplate.header(contextutil.request_context, json.tojsonstring(contextutil.getcurrentcontext()));
        }
    } 
}

3~ http

最后一类,也是用得最少的一类,即直接通过http发送请求。比如closeablehttpclient,resttemplate。解决方案直接见代码:

//resttemplate
httpheaders headers = new httpheaders();
headers.set(contextutil.request_context,jsonobject.tojsonstring(contextutil.getcurrentcontext()));
 
//closeablehttpclient
httpget httpget = new httpget(uri);
httpget.setheader(contextutil.request_context,jsonobject.tojsonstring(contextutil.getcurrentcontext()));

只需要粗暴地在发送头部中增加header即可,而其请求上下文直接通过当前线程上下文获取即可。

<3> 配置负载规则

完成了流量染色,下面就差服务发现了。服务发现基于注册中心nacos,因此需要修改负载规则。在这里,我们配置ribbon的负载规则,修改为自定义负载均衡器nacosweightloadbalancerrule。

 
    @bean
    @scope("prototype")
    public irule getribbonrule() {
        return new nacosweightloadbalancerrule();
    }
public class nacosweightloadbalancerrule extends abstractloadbalancerrule { 
    @override
    public server choose(object o) {
        dynamicserverlistloadbalancer loadbalancer = (dynamicserverlistloadbalancer) getloadbalancer();
        string name = loadbalancer.getname();
        try {
            instance instance = nacosnamingservice.getinstance(name);
            return new nacosserver(instance);
        } catch (nacosexception ee) {
            log.error("请求服务异常!异常信息:{}", ee);
        } catch (exception e) {
            log.error("请求服务异常!异常信息:{}", e);
        }
        return null;
    } 
}

从代码中可以看到,最终通过nacosnamingservice.getinstance()方法获取实例。

<4> 配置智能路由规则

上面的负载规则,最终调用的是nacosnamingservice.getinstance()方法,该方法里面定义了智能路由规则,主要功能是根据流量进行服务精准匹配。

规则如下:

1~开关判断:是否开启路由功能,没有则走nacos默认路由。

2~获取实例:根据流量,获取对应实例。其中,路由匹配按照一定的优先级进行匹配。

路由规则:ip优先 > 环境 + 组 > 环境 + 默认组

解释一下这个规则,首先是获取实例,需要先获取nacos上面的所有可用实例,然后遍历,从中选出一个最合适的实例。

然后ip优先的含义是,如果在本地调试服务,那么从本地直接访问网站,请求就会优先访问本地服务,那么就便于开发人员调试了,debug,本地开发都不是问题了!

其实是,环境 + 组,这个规则代表了如果存在对应的环境和组都相同的服务,那作为最符合的实例肯定优先返回,其实是环境 + 默认组,最后如果都没有,就访问基准环境(master)。

注:环境和组的概念对应nacos上的namespace和group,如有不懂,请自行查看nacos官方文档。

最终代码如下:

public class nacosnamingservice { 
    public instance getinstance(string servicename, string groupname) throws nacosexception {
        //1. 判断智能路由开关是否开启,没有走默认路由
        if (!isenable()) {
            return discoveryproperties.namingserviceinstance().selectonehealthyinstance(servicename, groupname);
        }
 
        context context = contextutil.getcurrentcontext();
        if (context == null) {
            return nacosnamingfactory.getnamingservice(commonconstant.env.master).selectonehealthyinstance(servicename);
        }
        //2. 获取实例
        return getinstance(servicename, context);
    }
 
    public instance getinstance(string servicename, context context) throws nacosexception {
        instance envandgroupinstance = null;
        instance envdefgroupinstance = null;
        instance defaultinstance = null;
        //2.1 获取所有可以调用的命名空间
        list<namespace> namespaces = nacosnamingfactory.getnamespaces();
        for (namespace namespace : namespaces) {
            string thisenvname = namespace.getnamespace();
            namingservice namingservice = nacosnamingfactory.getnamingservice(thisenvname);
            list<instance> instances = new arraylist<>();
            list<instance> instances1 = namingservice.selectinstances(servicename, true);
            list<instance> instances2 = namingservice.selectinstances(servicename, groupname, true);
            instances.addall(instances1);
            instances.addall(instances2);
            //2.2 路由匹配
            for (instance instance : instances) {
                // 优先本机匹配
                if (instance.getip().equals(clientip)) {
                    return instance;
                }
                string thisgroupname = null;
                string thisservicename = instance.getservicename();
                if (thisservicename != null && thisservicename.split("@@") != null) {
                    thisgroupname = thisservicename.split("@@")[0];
                }
                if (thisenvname.equals(envname) && thisgroupname.equals(groupname)) {
                    envandgroupinstance = instance;
                }
                if (thisenvname.equals(envname) && thisgroupname.equals(commonconstant.default_group)) {
                    envdefgroupinstance = instance;
                }
                if (thisenvname.equals(commonconstant.env.master) && thisgroupname.equals(commonconstant.default_group)) {
                    defaultinstance = instance;
                }
            }
        }
        if (envandgroupinstance != null) {
            return envandgroupinstance;
        }
        if (envdefgroupinstance != null) {
            return envdefgroupinstance;
        }
        return defaultinstance;
    }
 
    @autowired
    private nacosdiscoveryproperties discoveryproperties; 
}

<5> 配置智能路由定时任务

刚才在介绍智能路由的匹配规则时,提到“获取所有可以调用的命名空间”。这是因为,nacos上可能有很多个命名空间namespace,而我们需要把所有namespace上的所有可用服务都获取到,而nacos源码中,一个namespace对应一个namingservice。因此我们需要定时获取nacos上所有的namingservice,存储到本地,再通过namingservice去获取实例。因此我们的做法是,配置一个监听器,定期监听nacos上的namespace变化,然后定期更新,维护到服务的内部缓存中。代码如下:

slf4j
@configuration
@conditionalonrouteenabled
public class routeautoconfiguration {
 
    @autowired(required = false)
    private routeproperties routeproperties;
 
    @postconstruct
    public void init() {
        log.info("初始化智能路由!");
        nacosnamingfactory.initnamespace();
        addlistener();
    }
 
    private void addlistener() {
        int period = routeproperties.getperiod();
        nacosexecutorservice nacosexecutorservice = new nacosexecutorservice("namespace-listener");
        nacosexecutorservice.execute(period);
    } 
}
 
    public static void initnamespace() {
        applicationcontext applicationcontext = springcontextutil.getcontext();
        if (applicationcontext == null) {
            return;
        }
        string serveraddr = applicationcontext.getenvironment().getproperty("spring.cloud.nacos.discovery.server-addr");
        if (serveraddr == null) {
            throw new runtimeexception("nacos地址为空!");
        }
        string url = serveraddr + "/nacos/v1/console/namespaces?namespaceid=";
        restresult<string> restresult = httputil.dogetjson(url, restresult.class);
        list<namespace> namespaces = json.parsearray(jsonobject.tojsonstring(restresult.getdata()), namespace.class);;
        nacosnamingfactory.setnamespaces(namespaces);
    }
public class nacosexecutorservice { 
    public void execute(int period) {
        executorservice.schedulewithfixeddelay(new nacosworker(), 5, period, timeunit.seconds);
    } 
    public nacosexecutorservice(string name) {
        executorservice = executors.newscheduledthreadpool(runtime.getruntime().availableprocessors(), new threadfactory() {
            @override
            public thread newthread(runnable r) {
                thread t = new thread(r);
                t.setname("jdh-system-" + name);
                t.setdaemon(true);
                return t;
            }
        });
    } 
    final scheduledexecutorservice executorservice; 
}

四. 遇到的难点

下面是智能路由实现过程,遇到的一些问题及解决方案。

问题1namespace启动了太多线程,导致线程数过大?

因为服务需要维护过多的namespace,每个namespace内部又启动多个线程维护服务实例信息,导致服务总线程数过大。

解决方案每个namespace设置只启动2个线程,通过下列参数设置:

properties.setproperty(propertykeyconst.naming_client_beat_thread_count, "1");
properties.setproperty(propertykeyconst.naming_polling_thread_count, "1");

问题2支持一个线程调用多个服务?

每个请求都会创建一个线程,这个线程可能会调用多次其他服务。

解决方案既然调用多次,那就创建上下文,并保持上下文,调用结束后再清除。见代码:

try {
    filterchain.dofilter(servletrequest, servletresponse);
} finally {
    contextutil.clear();
}

问题3:多应用支持:tomcat,springboot,gateway?

我们内部有多种框架,如何保证这些不同框架服务的支持?

解决方案针对不同应用,开发不同的starter包。

问题4:springboot版本兼容问题

解决方案:针对1.x和2.x单独开发starter包。

五. 带来的收益

1. 经济价值

同样的资源,多部署了n套环境,极大提高资源利用率。(毕竟增量环境和全量环境的代价还是相差很大的)

2. 研发价值

本地开发排查测试问题方便,极大提高研发效率。前面提到的ip优先规则,保证了这一点。本地请求总是最优先打到本地上。

3. 测试价值

多部署n套环境,支持更多版本,提高测试效率。同时只需要部署增量应用,也提高部署效率。

六. 总结

通过智能路由,我司实现了部署成本大幅减少,部署效率大幅提高,研发测试效率大幅提高。

最后总结下智能路由的主要功能:

1. 多环境管理:支持多环境路由,除了基准环境外,其他环境只部署增量应用。

2. 多用户支持:支持多用户公用一套环境,避免开发不同版本造成的冲突。

3. 前端研发路由:对前端研发人员,可以方便快捷地同一个任意后端人员对接。

4. 后端研发路由:对后端研发人员,无论什么环境都可以快速调试,快速发现问题。

5. 友好且兼容:对微服务无侵入性,且支持 web、webflux、tomcat等应用。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持www.887551.com。