Spring Cloud 學(xué)習(xí)(23) --- Zuul(五) 動(dòng)態(tài)路由、灰度發(fā)布

在了解了動(dòng)態(tài)路由的改造原理、方式后,就可以自實(shí)現(xiàn)一個(gè)小 demo??梢允褂?mysql 作為持久化方式,目的是方面、易于管理。

動(dòng)態(tài)路由實(shí)戰(zhàn)

源碼:https://gitee.com/laiyy0728/spring-cloud/tree/master/spring-cloud-zuul/spring-cloud-dynamic-route-zuul-server

Zuul Server

<dependencies>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-zuul</artifactId>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
</dependencies>
spring:
  application:
    name: spring-cloud-dynamic-route-zuul-server
  datasource:
    url: jdbc:mysql://localhost:3306/springcloud?useUnicode=true&characterEncoding=utf-8&serverTimezone=Hongkong
    driver-class-name: com.mysql.cj.jdbc.Driver
    username: root
    password: 123456
  jpa:
    hibernate:
      ddl-auto: update
server:
  port: 5555
eureka:
  instance:
    instance-id: ${spring.application.name}:${server.port}
    prefer-ip-address: true
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/
// zuul 路由實(shí)體
@Entity
@Table(name = "zuul_route")
@Data
public class ZuulRouteEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;

    private String path;

    @Column(name = "service_id")
    private String serviceId;
    private String url;

    @Column(name = "strip_prefix")
    private boolean stripPrefix = true;
    private boolean retryable;
    private boolean enabled;
    private String description;
}


// dao
public interface ZuulPropertiesDao extends JpaRepository<ZuulRouteEntity, Integer> {

    @Query("FROM ZuulRouteEntity WHERE enabled = TRUE")
    List<ZuulRouteEntity> findAllByParams();

}


// 動(dòng)態(tài)路由實(shí)現(xiàn)
public class DynamicZuulRouteLocator extends SimpleRouteLocator implements RefreshableRouteLocator {

    @Autowired
    private ZuulProperties zuulProperties;

    @Autowired
    private ZuulPropertiesDao zuulPropertiesDao;

    public DynamicZuulRouteLocator(String servletPath, ZuulProperties properties) {
        super(servletPath, properties);
        this.zuulProperties = properties;
    }

    @Override
    public void refresh() {
        doRefresh();
    }

    @Override
    protected Map<String, ZuulProperties.ZuulRoute> locateRoutes() {
        Map<String, ZuulProperties.ZuulRoute> routeMap = new LinkedHashMap<>();
        routeMap.putAll(super.locateRoutes());
        routeMap.putAll(getProperties());
        Map<String, ZuulProperties.ZuulRoute> values = new LinkedHashMap<>();
        routeMap.forEach((path, zuulRoute) -> {
            path = path.startsWith("/") ? path : "/" + path;
            if (StringUtils.hasText(this.zuulProperties.getPrefix())) {
                path = this.zuulProperties.getPrefix() + path;
                path = path.startsWith("/") ? path : "/" + path;
            }
            values.put(path, zuulRoute);
        });
        return values;
    }

    private Map<String, ZuulProperties.ZuulRoute> getProperties() {
        Map<String, ZuulProperties.ZuulRoute> routeMap = new LinkedHashMap<>();
        List<ZuulRouteEntity> list = zuulPropertiesDao.findAllByParams();
        list.forEach(entity -> {
            if (org.apache.commons.lang.StringUtils.isBlank(entity.getPath())) {
                return;
            }
            ZuulProperties.ZuulRoute route = new ZuulProperties.ZuulRoute();
            BeanUtils.copyProperties(entity, route);
            route.setId(String.valueOf(entity.getId()));
            routeMap.put(route.getPath(), route);
        });
        return routeMap;
    }
}


// 注冊到 Spring
@Configuration
public class DynamicZuulConfig {

    private final ZuulProperties zuulProperties;

    private final ServerProperties serverProperties;

    @Autowired
    public DynamicZuulConfig(ZuulProperties zuulProperties, ServerProperties serverProperties) {
        this.zuulProperties = zuulProperties;
        this.serverProperties = serverProperties;
    }

    @Bean
    public DynamicZuulRouteLocator dynamicZuulRouteLocator(){
        return new DynamicZuulRouteLocator(serverProperties.getServlet().getContextPath(), zuulProperties);
    }
}

驗(yàn)證

在數(shù)據(jù)庫中增加三條數(shù)據(jù)

INSERT INTO `springcloud`.`zuul_route` (`id`, `description`, `enabled`, `path`, `retryable`, `service_id`, `strip_prefix`, `url`) VALUES ('1', '重定向到百度', '\1', '/baidu/**', '\0', NULL, '\1', 'http://www.baidu.com');
INSERT INTO `springcloud`.`zuul_route` (`id`, `description`, `enabled`, `path`, `retryable`, `service_id`, `strip_prefix`, `url`) VALUES ('2', 'url', '\1', '/client/**', '\0', NULL, '\1', 'http://localhost:8081');
INSERT INTO `springcloud`.`zuul_route` (`id`, `description`, `enabled`, `path`, `retryable`, `service_id`, `strip_prefix`, `url`) VALUES ('3', 'serviceId', '\1', '/client-1/**', '\0', 'client-a', '\1', NULL);

訪問 http://localhost:5555/baidu/get-resulthttp://localhost:5555/client/get-resulthttp://localhost:5555/client-a/get-result

重定向百度

this is provider service! this port is: 8081 headers: [user-agent]: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36; [cache-control]: no-cache; [postman-token]: a35929aa-9bcf-f5e4-b79a-0e684b1611ed; [token]: E477CA7B8E7CDCDCE3331742544DE9F1; [content-type]: application/x-www-form-urlencoded;charset=UTF-8; [accept]: */*; [accept-encoding]: gzip, deflate, br; [accept-language]: zh-CN,zh;q=0.9; [x-forwarded-host]: localhost:5555; [x-forwarded-proto]: http; [x-forwarded-prefix]: /client; [x-forwarded-port]: 5555; [x-forwarded-for]: 0:0:0:0:0:0:0:1; [host]: localhost:8081; [connection]: Keep-Alive; 
{
    "timestamp": "2019-02-21T03:15:18.997+0000",
    "status": 404,
    "error": "Not Found",
    "message": "No message available",
    "path": "/client-a/get-result"
}

由此可以證明,動(dòng)態(tài)路由配置成功。


灰度發(fā)布

灰度發(fā)布是指在系統(tǒng)迭代新功能時(shí)的一種平滑過渡的上線發(fā)布方式?;叶劝l(fā)布是在原有的系統(tǒng)基礎(chǔ)上,額外增加一個(gè)新版本,在這個(gè)新版本中,有需要驗(yàn)證的功能修改或添加,使用負(fù)載均衡器,引入一小部分流量到新版本應(yīng)用中,如果這個(gè)新版本沒有出現(xiàn)差錯(cuò),再平滑地把線上系統(tǒng)或服務(wù)一步步替換成新版本,直至全部替換上線結(jié)束。

灰度發(fā)布實(shí)現(xiàn)方式

灰度發(fā)布可以使用元數(shù)據(jù)來實(shí)現(xiàn),元數(shù)據(jù)有兩種

  • 標(biāo)準(zhǔn)元數(shù)據(jù):標(biāo)準(zhǔn)元數(shù)據(jù)是服務(wù)的各種注冊信息,如:ip、端口、健康信息、續(xù)約信息等,存儲(chǔ)于專門為服務(wù)開辟的注冊表中,用于其他組件取用以實(shí)現(xiàn)整個(gè)微服務(wù)生態(tài)
  • 自定義元數(shù)據(jù):自定義元數(shù)據(jù)是使用 eureka.instance.metadata-map.{key}={value} 配置,其內(nèi)部實(shí)際上是維護(hù)了一個(gè) map 來保存子彈元數(shù)據(jù)信息,可配置再遠(yuǎn)端服務(wù),隨服務(wù)一并注冊保存在 Eureka 注冊表,對微服務(wù)生態(tài)沒有影響。

灰度發(fā)布實(shí)戰(zhàn)

源碼:https://gitee.com/laiyy0728/spring-cloud/tree/master/spring-cloud-zuul/spring-cloud-zuul-metadata

provider

eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/
  instance:
    prefer-ip-address: true
    instance-id: ${spring.application.name}:${server.port}

spring:
  application:
    name: spring-cloud-metadata-provider-service

---
server:
  port: 7070
spring:
  profiles: node1   # 設(shè)定 profile,可以使用 mvn spring-boor:run -Dspring.profiles.active=node1 啟動(dòng),或者在啟動(dòng)類使用   SpringApplication.run(SpringCloudMetadataProviderServiceApplication.class, "--spring.profiles.active=node1"); 啟動(dòng)
eureka:
  instance:
    metadata-map:
      host-mark: running # 設(shè)定當(dāng)前節(jié)點(diǎn)的 metadata,zuul server 使用這個(gè)標(biāo)注來進(jìn)行路由轉(zhuǎn)發(fā)
---
spring:
  profiles: node2
server:
  port: 7071
eureka:
  instance:
    metadata-map:
      host-mark: running
---
spring:
  profiles: node3
server:
  port: 7072
eureka:
  instance:
    metadata-map:
      host-mark: gray  # 當(dāng)前節(jié)點(diǎn)是灰度節(jié)點(diǎn)
@SpringBootApplication
@EnableDiscoveryClient
@RestController
public class SpringCloudMetadataProviderServiceApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringCloudMetadataProviderServiceApplication.class, args);
        // SpringApplication.run(SpringCloudMetadataProviderServiceApplication.class, "--Dspring.profiles.active=node1"); // 非 maven 啟動(dòng)
    }

    @Value("${server.port}")
    private int port;

    @GetMapping(value = "/get-result")
    public String getResult(){
        return "metadata provider service result, port: " + port;
    }
}

Zuul Server

<dependencies>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-zuul</artifactId>
    </dependency>

    <!-- 實(shí)現(xiàn)通過 metadata 進(jìn)行灰度路由 -->
    <dependency>
        <groupId>io.jmnarloch</groupId>
        <artifactId>ribbon-discovery-filter-spring-cloud-starter</artifactId>
        <version>2.1.0</version>
    </dependency>
</dependencies>
spring:
  application:
    name: spring-cloud-metadata-zuul-server
server:
  port: 5555
eureka:
  instance:
    instance-id: ${spring.application.name}:${server.port}
    prefer-ip-address: true
  client:
    service-url:
      defautlZone: http://localhost:8761/eureka/
zuul:
  routes:
    spring-cloud-metadata-provider-service:
      path: /provider/**
      serviceId: spring-cloud-metadata-provider-service
management:
  endpoints:
    web:
      exposure:
        include: '*'
  endpoint:
    health:
      show-details: always
// 實(shí)現(xiàn)灰度的 Filter
public class GrayFilter extends ZuulFilter {

    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return FilterConstants.PRE_DECORATION_FILTER_ORDER - 1;
    }

    @Override
    public boolean shouldFilter() {
        RequestContext context = RequestContext.getCurrentContext();
        return !context.containsKey(FilterConstants.FORWARD_TO_KEY) && !context.containsKey(FilterConstants.SERVICE_ID_KEY);
    }

    @Override
    public Object run() throws ZuulException {
        HttpServletRequest request = RequestContext.getCurrentContext().getRequest();
        String grayMark = request.getHeader("gray_mark");
        if (StringUtils.isNotBlank(grayMark) && StringUtils.equals("enable", grayMark)) {
            RibbonFilterContextHolder.getCurrentContext().add("host-mark", "gray");
        } else {
            RibbonFilterContextHolder.getCurrentContext().add("host-mark", "running");
        }
        return null;
    }
}


@SpringBootApplication
@EnableDiscoveryClient
@EnableZuulProxy
public class SpringCloudMetadataZuulServerApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringCloudMetadataZuulServerApplication.class, args);
    }

    @Bean
    public GrayFilter grayFilter(){
        return new GrayFilter();
    }

}

驗(yàn)證

正常訪問: http://localhost:5555/provider/get-result ,查看返回值, port 在 7070 和 7071 之間輪詢。

gray running

啟用 gray_mark header,再次訪問,發(fā)現(xiàn) port 始終都是 7072,由此驗(yàn)證灰度成功


gray
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容