zuul动态配置路由规则,从DB读取

前面已经讲过zuul在application.yml里配置路由规则,将用户请求分发至不一样微服务的例子。java

zuul做为一个网关,是用户请求的入口,担当鉴权、转发的重任,理应保持高可用性和具有动态配置的能力。web

我画了一个实际中可能使用的配置框架,如图。spring

图片.png

当用户发起请求后,首先经过并发能力强、能承担更多用户请求的负载均衡器进行第一步的负载均衡,将大量的请求分发至多个网关服务。这是分布式的第一步。若是是使用docker的话,而且使用rancher进行docker管理,那么能够很简单的使用rancher自带的负载均衡,建立HaProxy,将请求分发至多个Zuul的docker容器。使用多个zuul的缘由便是避免单点故障,因为网关很是重要,尽可能配置多个实例。docker

而后在Zuul网关中,执行完自定义的网关职责后,将请求转发至另外一个HaProxy负载的微服务集群,一样是避免微服务单点故障和性能瓶颈。数据库

最后由具体的微服务处理用户请求并返回结果。api

那么为何要设置zuul的动态配置呢,由于网关其特殊性,咱们不但愿它重启再加载新的配置,并且若是能实时动态配置,咱们就能够完成无感知的微服务迁移替换,在某种程度还能够完成服务降级的功能。并发

zuul的动态配置也很简单,这里咱们参考http://blog.csdn.net/u013815546/article/details/68944039 并使用他的方法,从数据库读取配置信息,刷新配置。app


看实现类负载均衡

配置文件里咱们能够不配置zuul的任何路由,所有交给数据库配置。框架

 
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.cloud.netflix.zuul.filters.RefreshableRouteLocator;
import org.springframework.cloud.netflix.zuul.filters.SimpleRouteLocator;
import org.springframework.cloud.netflix.zuul.filters.ZuulProperties;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.util.StringUtils;
 
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
 
public class CustomRouteLocator extends SimpleRouteLocator implements RefreshableRouteLocator {
 
    public final static Logger logger = LoggerFactory.getLogger(CustomRouteLocator.class);
 
    private JdbcTemplate jdbcTemplate;
 
    private ZuulProperties properties;
 
    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }
 
    public CustomRouteLocator(String servletPath, ZuulProperties properties) {
        super(servletPath, properties);
        this.properties = properties;
        logger.info("servletPath:{}", servletPath);
    }
 
    //父类已经提供了这个方法,这里写出来只是为了说明这一个方法很重要!!!
//    @Override
//    protected void doRefresh() {
//        super.doRefresh();
//    }
 
 
    @Override
    public void refresh() {
        doRefresh();
    }
 
    @Override
    protected Map<String, ZuulProperties.ZuulRoute> locateRoutes() {
        LinkedHashMap<String, ZuulProperties.ZuulRoute> routesMap = new LinkedHashMap<>();
        //从application.properties中加载路由信息
        routesMap.putAll(super.locateRoutes());
        //从db中加载路由信息
        routesMap.putAll(locateRoutesFromDB());
        //优化一下配置
        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;
    }
 
    private Map<String, ZuulProperties.ZuulRoute> locateRoutesFromDB() {
        Map<String, ZuulProperties.ZuulRoute> routes = new LinkedHashMap<>();
        List<ZuulRouteVO> results = jdbcTemplate.query("select * from gateway_api_define where enabled = true ", new
                BeanPropertyRowMapper<>(ZuulRouteVO.class));
        for (ZuulRouteVO result : results) {
            if (StringUtils.isEmpty(result.getPath()) ) {
                continue;
            }
            if (StringUtils.isEmpty(result.getServiceId()) && StringUtils.isEmpty(result.getUrl())) {
                continue;
            }
            ZuulProperties.ZuulRoute zuulRoute = new ZuulProperties.ZuulRoute();
            try {
                BeanUtils.copyProperties(result, zuulRoute);
            } catch (Exception e) {
                logger.error("=============load zuul route info from db with error==============", e);
            }
            routes.put(zuulRoute.getPath(), zuulRoute);
        }
        return routes;
    }
 
    public static class ZuulRouteVO {
 
        /**
         * The ID of the route (the same as its map key by default).
         */
        private String id;
 
        /**
         * The path (pattern) for the route, e.g. /foo/**.
         */
        private String path;
 
        /**
         * The service ID (if any) to map to this route. You can specify a physical URL or
         * a service, but not both.
         */
        private String serviceId;
 
        /**
         * A full physical URL to map to the route. An alternative is to use a service ID
         * and service discovery to find the physical address.
         */
        private String url;
 
        /**
         * Flag to determine whether the prefix for this route (the path, minus pattern
         * patcher) should be stripped before forwarding.
         */
        private boolean stripPrefix = true;
 
        /**
         * Flag to indicate that this route should be retryable (if supported). Generally
         * retry requires a service ID and ribbon.
         */
        private Boolean retryable;
 
        private Boolean enabled;
 
        public String getId() {
            return id;
        }
 
        public void setId(String id) {
            this.id = id;
        }
 
        public String getPath() {
            return path;
        }
 
        public void setPath(String path) {
            this.path = path;
        }
 
        public String getServiceId() {
            return serviceId;
        }
 
        public void setServiceId(String serviceId) {
            this.serviceId = serviceId;
        }
 
        public String getUrl() {
            return url;
        }
 
        public void setUrl(String url) {
            this.url = url;
        }
 
        public boolean isStripPrefix() {
            return stripPrefix;
        }
 
        public void setStripPrefix(boolean stripPrefix) {
            this.stripPrefix = stripPrefix;
        }
 
        public Boolean getRetryable() {
            return retryable;
        }
 
        public void setRetryable(Boolean retryable) {
            this.retryable = retryable;
        }
 
        public Boolean getEnabled() {
            return enabled;
        }
 
        public void setEnabled(Boolean enabled) {
            this.enabled = enabled;
        }
    }
}



package com.tianyalei.testzuul.config;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.cloud.netflix.zuul.filters.ZuulProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
 
@Configuration
public class CustomZuulConfig {
 
    @Autowired
    ZuulProperties zuulProperties;
    @Autowired
    ServerProperties server;
    @Autowired
    JdbcTemplate jdbcTemplate;
 
    @Bean
    public CustomRouteLocator routeLocator() {
        CustomRouteLocator routeLocator = new CustomRouteLocator(this.server.getServletPrefix(), this.zuulProperties);
        routeLocator.setJdbcTemplate(jdbcTemplate);
        return routeLocator;
    }
 
}

下面的config类功能就是使用自定义的RouteLocator类,上面的类就是这个自定义类。

里面主要是一个方法,locateRoutes方法,该方法就是zuul设置路由规则的地方,在方法里作了2件事,一是从application.yml读取配置的路由信息,二是从数据库里读取路由信息,因此数据库里须要一个各字段和ZuulProperties.ZuulRoute同样的表,存储路由信息,从数据库读取后添加到系统的Map<String, ZuulProperties.ZuulRoute>中。

在实际的路由中,zuul就是按照Map<String, ZuulProperties.ZuulRoute>里的信息进行路由转发的。

建表语句:

create table `gateway_api_define` (
  `id` varchar(50) not null,
  `path` varchar(255) not null,
  `service_id` varchar(50) default null,
  `url` varchar(255) default null,
  `retryable` tinyint(1) default null,
  `enabled` tinyint(1) not null,
  `strip_prefix` int(11) default null,
  `api_name` varchar(255) default null,
  primary key (`id`)
) engine=innodb default charset=utf8
 
 
INSERT INTO gateway_api_define (id, path, service_id, retryable, strip_prefix, url, enabled) VALUES ('user', '/user/**', null,0,1, 'http://localhost:8081', 1);
INSERT INTO gateway_api_define (id, path, service_id, retryable, strip_prefix, url, enabled) VALUES ('club', '/club/**', null,0,1, 'http://localhost:8090', 1);

经过上面的两个类,再结合前面几篇讲过的zuul的使用,就能够自行测试一下在数据库里配置的信息可否在zuul中生效了。

数据库里的各字段分别对应本来在yml里配置的同名属性,如path,service_id,url等,等于把配置文件存到数据库里。

至于修改数据库值信息后(增删改),让zuul动态生效须要借助于下面的方法

package com.tianyalei.testzuul.config;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.RoutesRefreshedEvent;
import org.springframework.cloud.netflix.zuul.filters.RouteLocator;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
 
@Service
public class RefreshRouteService {
    @Autowired
    ApplicationEventPublisher publisher;
 
    @Autowired
    RouteLocator routeLocator;
 
    public void refreshRoute() {
        RoutesRefreshedEvent routesRefreshedEvent = new RoutesRefreshedEvent(routeLocator);
        publisher.publishEvent(routesRefreshedEvent);
    }
}

能够定义一个Controller,在Controller里调用refreshRoute方法便可,zuul就会从新加载一遍路由信息,完成刷新功能。经过修改数据库,而后刷新,经测试是正常的。

@RestController
public class RefreshController {
    @Autowired
    RefreshRouteService refreshRouteService;
    @Autowired
    ZuulHandlerMapping zuulHandlerMapping;
 
    @GetMapping("/refreshRoute")
    public String refresh() {
        refreshRouteService.refreshRoute();
        return "refresh success";
    }
 
    @RequestMapping("/watchRoute")
    public Object watchNowRoute() {
        //能够用debug模式看里面具体是什么
        Map<String, Object> handlerMap = zuulHandlerMapping.getHandlerMap();
        return handlerMap;
    }
 
}

参考http://blog.csdn.net/u013815546/article/details/68944039,做者从源码角度讲解了动态配置的使用。

https://blog.csdn.net/tianyaleixiaowu/article/details/77933295?locationNum=5&fps=1

相关文章
相关标签/搜索