[轉] zuul動態配置路由規則,從DB讀取
原文地址:https://blog.csdn.net/tianyaleixiaowu/article/details/77933295?locationNum=5&fps=1
原文作者: https://blog.csdn.net/tianyaleixiaowu
前面已經講過zuul在application.yml裡配置路由規則,將使用者請求分發至不同微服務的例子。
zuul作為一個閘道器,是使用者請求的入口,擔當鑑權、轉發的重任,理應保持高可用性和具備動態配置的能力。
我畫了一個實際中可能使用的配置框架,如圖。
當用戶發起請求後,首先通過併發能力強、能承擔更多使用者請求的負載均衡器進行第一步的負載均衡,將大量的請求分發至多個閘道器服務。這是分散式的第一步。如果是使用docker的話,並且使用rancher進行docker管理,那麼可以很簡單的使用rancher自帶的負載均衡,建立HaProxy,將請求分發至多個Zuul的docker容器。使用多個zuul的原因即是避免單點故障,由於閘道器非常重要,儘量配置多個例項。
然後在Zuul閘道器中,執行完自定義的閘道器職責後,將請求轉發至另一個HaProxy負載的微服務叢集,同樣是避免微服務單點故障和效能瓶頸。
最後由具體的微服務處理使用者請求並返回結果。
那麼為什麼要設定zuul的動態配置呢,因為閘道器其特殊性,我們不希望它重啟再載入新的配置,而且如果能實時動態配置,我們就可以完成無感知的微服務遷移替換,在某種程度還可以完成服務降級的功能。
zuul的動態配置也很簡單,這裡我們參考http://blog.csdn.net/u013815546/article/details/68944039 並使用他的方法,從資料庫讀取配置資訊,重新整理配置。
看實現類
配置檔案裡我們可以不配置zuul的任何路由,全部交給資料庫配置。
- package com.tianyalei.testzuul.config;
- 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();
- // }
- public void refresh() {
- doRefresh();
- }
- 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;
- public class CustomZuulConfig {
- ZuulProperties zuulProperties;
- ServerProperties server;
- JdbcTemplate jdbcTemplate;
- 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;
- public class RefreshRouteService {
- ApplicationEventPublisher publisher;
- RouteLocator routeLocator;
- public void refreshRoute() {
- RoutesRefreshedEvent routesRefreshedEvent = new RoutesRefreshedEvent(routeLocator);
- publisher.publishEvent(routesRefreshedEvent);
- }
- }
- public class RefreshController {
- RefreshRouteService refreshRouteService;
- ZuulHandlerMapping zuulHandlerMapping;
- "/refreshRoute") (
- public String refresh() {
- refreshRouteService.refreshRoute();
- return "refresh success";
- }
- "/watchRoute") (
- public Object watchNowRoute() {
- //可以用debug模式看裡面具體是什麼
- Map<String, Object> handlerMap = zuulHandlerMapping.getHandlerMap();
- return handlerMap;
- }
- }
參考http://blog.csdn.net/u013815546/article/details/68944039,作者從原始碼角度講解了動態配置的使用。