Netflix Zuul结合Disconf实现动态路由刷新

公司使用Disconf来管理分布式配置,Disconf使用zookeeper来提供配置存储,同时预留了通知接口以接收配置变更。

1.配置Disconf更新通知入口

Disconf预留有IDisconfUpdatePipeline接口,实现该接口可以在Disconf控制台保存的配置文件发生变更时实时得到消息, 代码如下:

@Slf4j
@Service
@Scope("singleton")
public class CustomDisconfReloadUpdate implements IDisconfUpdatePipeline {

    /**
     * Store changed configuration file's path
     */
    private static final ThreadLocal<String> newConfigFilePath = new ThreadLocal<>();

    @Autowired
    ApplicationEventPublisher publisher;

    @Autowired
    RouteLocator routeLocator;

    /**
     * 发布zuul refresh事件
     */
    public void refreshRoute() {
        RoutesRefreshedEvent routesRefreshedEvent = new RoutesRefreshedEvent(routeLocator);
        publisher.publishEvent(routesRefreshedEvent);
    }

    @Override
    public void reloadDisconfFile(String key, String filePath) throws Exception {
        log.info("------Got reload event from disconf------");
        log.info("Change key: {}, filePath: {}", key, filePath);
        newConfigFilePath.set(filePath);
        refreshRoute();
    }

    @Override
    public void reloadDisconfItem(String key, Object content) throws Exception {
        log.info("------Got reload event from disconf with item------");
        log.info("Change key: {}, content: {}", key, content);
    }

    /**
     * Checkout configFilePath and remove the ThreadLocal value content
     * @return
     */
    public static String getConfigFilePath() {
        String path = newConfigFilePath.get();
        newConfigFilePath.remove();
        return path;
    }
}
  • 1.使用ThreadLocal来保存变更了的配置文件在本地的路径以供线程后续执行时读取使用
  • 2.使用RoutesRefreshedEvent事件机制来刷新Zuul的路由表

2.自定义RouteLocator实现路由表刷新功能

Zuul默认使用的是SimpleRouteLocator作为路由发现入口,然而并不支持动态刷新;Zuul预留了RefreshableRouteLocator接口以支持动态路由表刷新,以下是自定义类实现路由刷新功能:

@Slf4j
public class CustomZuulRouteLocator extends SimpleRouteLocator implements RefreshableRouteLocator {

    private ZuulProperties properties;
    private SpringClientFactory springClientFactory;

    public CustomZuulRouteLocator(String servletPath, ZuulProperties properties, SpringClientFactory springClientFactory) {
        super(servletPath, properties);
        this.properties = properties;
        this.springClientFactory = springClientFactory;
    }

    @Override
    public void refresh() {
        doRefresh();
    }

    @Override
    protected Map<String, ZuulProperties.ZuulRoute> locateRoutes() {
        LinkedHashMap<String, ZuulProperties.ZuulRoute> routesMap = new LinkedHashMap<>();
        // This will load the old routes which exist in cache
        routesMap.putAll(super.locateRoutes());
        try {
            // If server can load routes from file which means the file changed, using the new config routes
            Map<String, ZuulProperties.ZuulRoute> newRouteMap = loadRoutesFromDisconf();
            if(newRouteMap.size() > 0) {
                log.info("New config services list: {}", Arrays.toString(newRouteMap.keySet().toArray()));
                routesMap.clear();
                routesMap.putAll(newRouteMap);
            }
        } catch (Exception e) {
            // For every exception, do not break the gateway working
            log.error(e.getMessage(), e);
        }
        LinkedHashMap<String, ZuulProperties.ZuulRoute> values = new LinkedHashMap<>();
        for (Map.Entry<String, ZuulProperties.ZuulRoute> entry : routesMap.entrySet()) {
            String path = entry.getKey();
            // Prepend with slash if not already present.
            if (!path.startsWith("/")) {
                path = "/" + path;
            }
            if (StringUtils.hasText(this.properties.getPrefix())) {
                path = this.properties.getPrefix() + path;
                if (!path.startsWith("/")) {
                    path = "/" + path;
                }
            }
            values.put(path, entry.getValue());
        }
        return values;
    }

    /**
     * Read the new config file and reload new route and service config
     * @return
     */
    private Map<String, ZuulProperties.ZuulRoute> loadRoutesFromDisconf() {
        log.info("----load configuration----");
        Map<String, ZuulProperties.ZuulRoute> latestRoutes = new LinkedHashMap<>(16);
        String configFilePath = CustomDisconfReloadUpdate.getConfigFilePath();
        if(configFilePath != null) {
            String newConfigContent = readFileContent(configFilePath);
            ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory());
            try {
                Map<String, Object> configResult = objectMapper.readValue(newConfigContent, Map.class);
                // Store all serviceId with ribbon configuration
                List<String> allServiceIds = new ArrayList<>();
                // This Node used to deal with Zuul route configuration
                if(configResult.containsKey("zuul")) {
                    Map<String, Object> zuulConfig = (Map<String, Object>) configResult.get("zuul");
                    if(zuulConfig.containsKey("routes")) {
                        Map<String, Object> routes = (Map<String, Object>) zuulConfig.get("routes");
                        if(routes != null) {
                            for(Map.Entry<String, Object> tempRoute : routes.entrySet()) {
                                String id = tempRoute.getKey();
                                Map<String, Object> routeDetail = (Map<String, Object>) tempRoute.getValue();
                                ZuulProperties.ZuulRoute zuulRoute = generateZuulRoute(id, routeDetail);
                                // Got list with config serviceId
                                if(zuulRoute.getServiceId() != null) {
                                    allServiceIds.add(zuulRoute.getServiceId());
                                }
                                latestRoutes.put(zuulRoute.getPath(), zuulRoute);
                            }
                        }
                    }
                }
                // deal with all serviceIds and read properties from yaml configuraiton
                if(allServiceIds.size() > 0) {
                    allServiceIds.forEach(temp -> {
                        // Exist this serviceId
                        if(configResult.containsKey(temp)) {
                            Map<String, Object> serviceRibbonConfig = (Map<String, Object>) configResult.get(temp);
                            if(serviceRibbonConfig.containsKey("ribbon")) {
                                Map<String, Object> ribbonConfig = (Map<String, Object>) serviceRibbonConfig.get("ribbon");
                                if(ribbonConfig.containsKey("listOfServers")) {
                                    String listOfServers = (String) ribbonConfig.get("listOfServers");
                                    String ruleClass = (String) ribbonConfig.get("NFLoadBalancerRuleClassName");
                                    String[] serverList = listOfServers.split(",");
                                    dealLoadBalanceConfig(temp, ruleClass, Arrays.asList(serverList));
                                }
                            }
                        }
                    });
                }
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            }
        }
        return latestRoutes;
    }

    /**
     * Change loadbalancer's serverList configuration
     */
    private void dealLoadBalanceConfig(String serviceId, String newRuleClassName, List<String> servers) {
        DynamicServerListLoadBalancer loadBalancer = (DynamicServerListLoadBalancer) springClientFactory.getLoadBalancer(serviceId);
        if(loadBalancer != null) {
            // 1.Reset listOfServer content if listOfServers changed
            List<String> newServerList = new ArrayList<>();
            servers.forEach(temp -> {
                // remove the empty characters
                temp = temp.trim();
                newServerList.add(temp);
            });
            List<Server> oldServerList = loadBalancer.getServerListImpl().getUpdatedListOfServers();
            // Judge the listOfServers changed or not
            boolean serversChanged = false;
            if(oldServerList != null) {
                if(oldServerList.size() != newServerList.size()) {
                    serversChanged = true;
                } else {
                    for(Server temp : oldServerList) {
                        if(!newServerList.contains(temp.getId())) {
                            serversChanged = true;
                            break;
                        }
                    }
                }
            } else {
                serversChanged = true;
            }
            // listOfServers has changed
            if(serversChanged) {
                log.info("ServiceId: {} has changed listOfServers, new: {}", serviceId, Arrays.toString(servers.toArray()));
                loadBalancer.setServerListImpl(new ServerList<Server>() {
                    @Override
                    public List<Server> getInitialListOfServers() {
                        return null;
                    }

                    @Override
                    public List<Server> getUpdatedListOfServers() {
                        List<Server> newServerConfigList = new ArrayList<>();
                        newServerList.forEach(temp -> {
                            Server server = new Server(temp);
                            newServerConfigList.add(server);
                        });
                        // Using the new config listOfServers
                        return newServerConfigList;
                    }
                });
            }

            // Reset loadBalancer rule
            if(loadBalancer.getRule() != null) {
                String existRuleClassName = loadBalancer.getRule().getClass().getName();
                if(!newRuleClassName.equals(existRuleClassName)) {
                    log.info("ServiceId: {}, Old rule class: {}, New rule class: {}", serviceId, existRuleClassName, newRuleClassName);
                    initializeLoadBalancerWithNewRule(newRuleClassName, loadBalancer);
                }
            } else {
                initializeLoadBalancerWithNewRule(newRuleClassName, loadBalancer);
                log.info("ServiceId: {}, Old rule class: Null, Need rule class: {}", serviceId, newRuleClassName);
            }
        }
    }

    /**
     * Change loadBalancer's rule
     * @param ruleClassName
     * @param loadBalancer
     */
    private void initializeLoadBalancerWithNewRule(String ruleClassName, DynamicServerListLoadBalancer loadBalancer) {
        try {
            // Create specify class instance
            Class clazz = Class.forName(ruleClassName);
            Constructor constructor = clazz.getConstructor();
            IRule rule = (IRule) constructor.newInstance();
            // Bind loadBalancer with this Rule
            rule.setLoadBalancer(loadBalancer);
            loadBalancer.setRule(rule);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    /**
     * Generate zuul route object from configuration
     * @param id
     * @param routeDetail
     * @return
     */
    private ZuulProperties.ZuulRoute generateZuulRoute(String id, Map<String, Object> routeDetail) {
        ZuulProperties.ZuulRoute route = new ZuulProperties.ZuulRoute();
        route.setId(id);
        if(routeDetail.containsKey("path")) {
            route.setPath((String) routeDetail.get("path"));
        }
        if(routeDetail.containsKey("serviceId")) {
            route.setServiceId((String) routeDetail.get("serviceId"));
        }
        if(routeDetail.containsKey("url")) {
            route.setUrl((String) routeDetail.get("url"));
        }
        if(routeDetail.containsKey("stripPrefix")) {
            route.setStripPrefix((Boolean) routeDetail.get("stripPrefix"));
        }
        return route;
    }

    /**
     * Read config file from local file system
     * @param configFile
     * @return
     */
    private String readFileContent(String configFile) {
        try {
            FileInputStream inputStream = new FileInputStream(new File(configFile));
            String content = IOUtils.toString(inputStream, "UTF-8");
            return content;
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }
}
  • 1.在第一步中发布的refreshEvent最终会调用refresh()方法中的doRefresh()方法,而doRefresh()则在父类实现中调用locateRoutes()来获取新的路由表
  • 2.由于我司这里使用yaml配置文件,因此需要解析配置文件数据比较路由规则是否发生变更,这里使用的是jackson-dataformat-yaml解析
  • 3.由于我司使用Ribbon进行客户端负载均衡,因此在路由表发生变化的情况下,负载均衡的规则也有可能变化了,这部分的动态刷新需要通过修改DynamicServerListLoadBalancer来完成

3.替换默认的SimpleRouteLocator

在完成上述两步之后,Zuul的动态路由功能基本支持了,现在就差把系统默认的SimpleRouteLocator给替换成我们自己的实现类,只需使用Bean注解启用自定义类即可:

  @Bean
  public CustomZuulRouteLocator routeLocator() {
        CustomZuulRouteLocator customZuulRouteLocator = new CustomZuulRouteLocator(serverProperties.getServlet().getServletPrefix(), zuulProperties, springClientFactory);
        return customZuulRouteLocator;
    }

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 212,657评论 6 492
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,662评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 158,143评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,732评论 1 284
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,837评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,036评论 1 291
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,126评论 3 410
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,868评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,315评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,641评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,773评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,470评论 4 333
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,126评论 3 317
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,859评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,095评论 1 267
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,584评论 2 362
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,676评论 2 351

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,637评论 18 139
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,778评论 6 342
  • 传统路由配置 所谓的传统路由配置方式就是在不依赖与服务发现机制的情况下,通过在配置文件中具体制定每个路由表达式实例...
    二月_春风阅读 25,135评论 8 25
  • 原文链接:http://cloud.spring.io/spring-cloud-static/spring-cl...
    周靖峰阅读 2,066评论 0 4
  • 中考带队 昨天认场骄阳似火, 老师依然坚持到岗。 认真对待每位学生, 嘱咐学生注意事项。 直到学生全部到位, 没有...
    你健康我快乐_61fc阅读 252评论 0 3