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

相關文章
相關標籤/搜索