1. 程式人生 > >[轉] zuul動態配置路由規則,從DB讀取

[轉] 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的任何路由,全部交給資料庫配置。

  1. package com.tianyalei.testzuul.config;
  2. import org.slf4j.Logger;
  3. import org.slf4j.LoggerFactory;
  4. import org.springframework.beans.BeanUtils;
  5. import org.springframework.cloud.netflix.zuul.filters.RefreshableRouteLocator;
  6. import org.springframework.cloud.netflix.zuul.filters.SimpleRouteLocator;
  7. import org.springframework.cloud.netflix.zuul.filters.ZuulProperties;
  8. import org.springframework.jdbc.core.BeanPropertyRowMapper;
  9. import org.springframework.jdbc.core.JdbcTemplate;
  10. import org.springframework.util.StringUtils;
  11. import java.util.LinkedHashMap;
  12. import java.util.List;
  13. import java.util.Map;
  14. public class CustomRouteLocator extends SimpleRouteLocator implements RefreshableRouteLocator {
  15. public final static Logger logger = LoggerFactory.getLogger(CustomRouteLocator.class);
  16. private JdbcTemplate jdbcTemplate;
  17. private ZuulProperties properties;
  18. public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
  19. this.jdbcTemplate = jdbcTemplate;
  20. }
  21. public CustomRouteLocator(String servletPath, ZuulProperties properties) {
  22. super(servletPath, properties);
  23. this.properties = properties;
  24. logger.info("servletPath:{}", servletPath);
  25. }
  26. //父類已經提供了這個方法,這裡寫出來只是為了說明這一個方法很重要!!!
  27. // @Override
  28. // protected void doRefresh() {
  29. // super.doRefresh();
  30. // }
  31. @Override
  32. public void refresh() {
  33. doRefresh();
  34. }
  35. @Override
  36. protected Map<String, ZuulProperties.ZuulRoute> locateRoutes() {
  37. LinkedHashMap<String, ZuulProperties.ZuulRoute> routesMap = new LinkedHashMap<>();
  38. //從application.properties中載入路由資訊
  39. routesMap.putAll(super.locateRoutes());
  40. //從db中載入路由資訊
  41. routesMap.putAll(locateRoutesFromDB());
  42. //優化一下配置
  43. LinkedHashMap<String, ZuulProperties.ZuulRoute> values = new LinkedHashMap<>();
  44. for (Map.Entry<String, ZuulProperties.ZuulRoute> entry : routesMap.entrySet()) {
  45. String path = entry.getKey();
  46. // Prepend with slash if not already present.
  47. if (!path.startsWith("/")) {
  48. path = "/" + path;
  49. }
  50. if (StringUtils.hasText(this.properties.getPrefix())) {
  51. path = this.properties.getPrefix() + path;
  52. if (!path.startsWith("/")) {
  53. path = "/" + path;
  54. }
  55. }
  56. values.put(path, entry.getValue());
  57. }
  58. return values;
  59. }
  60. private Map<String, ZuulProperties.ZuulRoute> locateRoutesFromDB() {
  61. Map<String, ZuulProperties.ZuulRoute> routes = new LinkedHashMap<>();
  62. List<ZuulRouteVO> results = jdbcTemplate.query("select * from gateway_api_define where enabled = true ", new
  63. BeanPropertyRowMapper<>(ZuulRouteVO.class));
  64. for (ZuulRouteVO result : results) {
  65. if (StringUtils.isEmpty(result.getPath()) ) {
  66. continue;
  67. }
  68. if (StringUtils.isEmpty(result.getServiceId()) && StringUtils.isEmpty(result.getUrl())) {
  69. continue;
  70. }
  71. ZuulProperties.ZuulRoute zuulRoute = new ZuulProperties.ZuulRoute();
  72. try {
  73. BeanUtils.copyProperties(result, zuulRoute);
  74. } catch (Exception e) {
  75. logger.error("=============load zuul route info from db with error==============", e);
  76. }
  77. routes.put(zuulRoute.getPath(), zuulRoute);
  78. }
  79. return routes;
  80. }
  81. public static class ZuulRouteVO {
  82. /**
  83. * The ID of the route (the same as its map key by default).
  84. */
  85. private String id;
  86. /**
  87. * The path (pattern) for the route, e.g. /foo/**.
  88. */
  89. private String path;
  90. /**
  91. * The service ID (if any) to map to this route. You can specify a physical URL or
  92. * a service, but not both.
  93. */
  94. private String serviceId;
  95. /**
  96. * A full physical URL to map to the route. An alternative is to use a service ID
  97. * and service discovery to find the physical address.
  98. */
  99. private String url;
  100. /**
  101. * Flag to determine whether the prefix for this route (the path, minus pattern
  102. * patcher) should be stripped before forwarding.
  103. */
  104. private boolean stripPrefix = true;
  105. /**
  106. * Flag to indicate that this route should be retryable (if supported). Generally
  107. * retry requires a service ID and ribbon.
  108. */
  109. private Boolean retryable;
  110. private Boolean enabled;
  111. public String getId() {
  112. return id;
  113. }
  114. public void setId(String id) {
  115. this.id = id;
  116. }
  117. public String getPath() {
  118. return path;
  119. }
  120. public void setPath(String path) {
  121. this.path = path;
  122. }
  123. public String getServiceId() {
  124. return serviceId;
  125. }
  126. public void setServiceId(String serviceId) {
  127. this.serviceId = serviceId;
  128. }
  129. public String getUrl() {
  130. return url;
  131. }
  132. public void setUrl(String url) {
  133. this.url = url;
  134. }
  135. public boolean isStripPrefix() {
  136. return stripPrefix;
  137. }
  138. public void setStripPrefix(boolean stripPrefix) {
  139. this.stripPrefix = stripPrefix;
  140. }
  141. public Boolean getRetryable() {
  142. return retryable;
  143. }
  144. public void setRetryable(Boolean retryable) {
  145. this.retryable = retryable;
  146. }
  147. public Boolean getEnabled() {
  148. return enabled;
  149. }
  150. public void setEnabled(Boolean enabled) {
  151. this.enabled = enabled;
  152. }
  153. }
  154. }


  1. package com.tianyalei.testzuul.config;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.boot.autoconfigure.web.ServerProperties;
  4. import org.springframework.cloud.netflix.zuul.filters.ZuulProperties;
  5. import org.springframework.context.annotation.Bean;
  6. import org.springframework.context.annotation.Configuration;
  7. import org.springframework.jdbc.core.JdbcTemplate;
  8. @Configuration
  9. public class CustomZuulConfig {
  10. @Autowired
  11. ZuulProperties zuulProperties;
  12. @Autowired
  13. ServerProperties server;
  14. @Autowired
  15. JdbcTemplate jdbcTemplate;
  16. @Bean
  17. public CustomRouteLocator routeLocator() {
  18. CustomRouteLocator routeLocator = new CustomRouteLocator(this.server.getServletPrefix(), this.zuulProperties);
  19. routeLocator.setJdbcTemplate(jdbcTemplate);
  20. return routeLocator;
  21. }
  22. }

下面的config類功能就是使用自定義的RouteLocator類,上面的類就是這個自定義類。

裡面主要是一個方法,locateRoutes方法,該方法就是zuul設定路由規則的地方,在方法裡做了2件事,一是從application.yml讀取配置的路由資訊,二是從資料庫裡讀取路由資訊,所以資料庫裡需要一個各欄位和ZuulProperties.ZuulRoute一樣的表,儲存路由資訊,從資料庫讀取後新增到系統的Map<String, ZuulProperties.ZuulRoute>中。

在實際的路由中,zuul就是按照Map<String, ZuulProperties.ZuulRoute>裡的資訊進行路由轉發的。

建表語句:

  1. create table `gateway_api_define` (
  2. `id` varchar(50) not null,
  3. `path` varchar(255) not null,
  4. `service_id` varchar(50) default null,
  5. `url` varchar(255) default null,
  6. `retryable` tinyint(1) default null,
  7. `enabled` tinyint(1) not null,
  8. `strip_prefix` int(11) default null,
  9. `api_name` varchar(255) default null,
  10. primary key (`id`)
  11. ) engine=innodb default charset=utf8
  12. INSERT INTO gateway_api_define (id, path, service_id, retryable, strip_prefix, url, enabled) VALUES ('user', '/user/**', null,0,1, 'http://localhost:8081', 1);
  13. 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動態生效需要藉助於下面的方法

  1. package com.tianyalei.testzuul.config;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.cloud.netflix.zuul.RoutesRefreshedEvent;
  4. import org.springframework.cloud.netflix.zuul.filters.RouteLocator;
  5. import org.springframework.context.ApplicationEventPublisher;
  6. import org.springframework.stereotype.Service;
  7. @Service
  8. public class RefreshRouteService {
  9. @Autowired
  10. ApplicationEventPublisher publisher;
  11. @Autowired
  12. RouteLocator routeLocator;
  13. public void refreshRoute() {
  14. RoutesRefreshedEvent routesRefreshedEvent = new RoutesRefreshedEvent(routeLocator);
  15. publisher.publishEvent(routesRefreshedEvent);
  16. }
  17. }
可以定義一個Controller,在Controller裡呼叫refreshRoute方法即可,zuul就會重新載入一遍路由資訊,完成重新整理功能。通過修改資料庫,然後重新整理,經測試是正常的。
  1. @RestController
  2. public class RefreshController {
  3. @Autowired
  4. RefreshRouteService refreshRouteService;
  5. @Autowired
  6. ZuulHandlerMapping zuulHandlerMapping;
  7. @GetMapping("/refreshRoute")
  8. public String refresh() {
  9. refreshRouteService.refreshRoute();
  10. return "refresh success";
  11. }
  12. @RequestMapping("/watchRoute")
  13. public Object watchNowRoute() {
  14. //可以用debug模式看裡面具體是什麼
  15. Map<String, Object> handlerMap = zuulHandlerMapping.getHandlerMap();
  16. return handlerMap;
  17. }
  18. }

參考http://blog.csdn.net/u013815546/article/details/68944039,作者從原始碼角度講解了動態配置的使用。