在数据库表中设计一个【灰度发布启用表】(也可以用Apollo配置中心,Redis,Zookeeper实现)。

代码示例

  1. id | service_id | path | enable_gray_release
  2. 服务ID 路径 是否启用灰度发布
  3. CREATE TABLE `gray_release_config` (
  4. `id` int(11) NOT NULL AUTO_INCREMENT,
  5. `service_id` varchar(255) DEFAULT NULL,
  6. `path` varchar(255) DEFAULT NULL,
  7. `enable_gray_release` int(11) DEFAULT NULL,
  8. PRIMARY KEY (`id`)
  9. ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
  1. ## 在zuul里面加入下面的fiter包,可以在zuul的filter里定制ribbon的负载均衡策略
  2. <dependency>
  3. <groupId>io.jmnarloch</groupId>
  4. <artifactId>ribbon-discovery-filter-spring-cloud-starter</artifactId>
  5. <version>2.1.0</version>
  6. </dependency>
  1. ## 写一个zuulfilter,对每一个请求,zuul都会调用这个filter
  2. @Configuration
  3. public class GrayReleaseFilter extends ZuulFilter {
  4. @Autowired
  5. private JdbcTemplate jdbcTemplate;
  6. @Override
  7. public int filterOrder() {
  8. return PRE_DECORATION_FILTER_ORDER - 1;
  9. }
  10. @Override
  11. public String filterType() {
  12. return PRE_TYPE;
  13. }
  14. @Override
  15. public boolean shouldFilter() {
  16. }
  17. @Override
  18. public Object run() {
  19. RequestContext ctx = RequestContext.getCurrentContext();
  20. HttpServletRequest request = ctx.getRequest();
  21. Random random = new Random();
  22. int seed = random.getInt() * 100;
  23. if (seed = 50) {
  24. // put the serviceId in `RequestContext`
  25. RibbonFilterContextHolder.getCurrentContext()
  26. .add("version", "new");
  27. } else {
  28. RibbonFilterContextHolder.getCurrentContext()
  29. .add("version", "old");
  30. }
  31. return null;
  32. }
  33. }

逻辑流程图