淺談Spring Cloud Netflix-Ribbon灰度方案之Zuul網關灰度

Eureka默認集成瞭Ribbon,所以Ribbon的灰度實現原理就是借助服務註冊到Eureka中的eureka.instance.metadata-map的內容來進行匹配的。

Zuul網關的灰度實現也是借助瞭一個Ribbon的插件來實現,相對比較簡單。

項目環境說明:有兩個eureka的服務端(eureka-server),有兩個相同的後端服務(service-sms),有一個網關服務(cloud-zuul)。

1、網關的依賴:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.9.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.kevin</groupId>
    <artifactId>cloud-zuul</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>cloud-zuul</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
        <spring-cloud.version>Hoxton.SR10</spring-cloud.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <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>
            <version>2.2.7.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>io.jmnarloch</groupId>
            <artifactId>ribbon-discovery-filter-spring-cloud-starter</artifactId>
            <version>2.1.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
            <version>2.2.7.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.2</version>
        </dependency>
 
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.21</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.48</version>
        </dependency>
    </dependencies>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
 
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>
 
</project>

這裡我們用到的就是io.jmnarloch.ribbon-discovery-filter-spring-cloud-starter 這個插件包。需要註意的是,這個包引入之後,eureka-client自身帶的ribbon很多功能就被覆蓋瞭,而且不能再自定義IRule規則。因為這個包裡面會生成一個metadataAwareRule的IRule,因為spring默認是單例,所以如果再自定義IRule會出現沖突運行時報錯。

2、配置application.yaml

server:
  port: 9100
spring:
  application:
    name: cloud-zuul
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/test?characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
    username: root
    password: root
    dbcp2:
      initial-size: 5
      min-idle: 5
      max-total: 10
      max-wait-millis: 1000
      validation-query: select 1
      test-while-idle: true
      test-on-borrow: false
      test-on-return: false
 
eureka:
  client:
    service-url:
      defaultZone: http://eureka-7900:7900/eureka/
mybatis:
  mapper-locations: classpath:mapper/*.xml

說明: 我的eureka服務端是部署在域名eureka-7900端口7900。

3、springboot啟動類中添加@EnableZuulProxy

@SpringBootApplication
@EnableZuulProxy
public class CloudZuulApplication {
 
    public static void main(String[] args) {
        SpringApplication.run(CloudZuulApplication.class, args);
    }
}

4、添加灰度過濾器

import com.kevin.dao.CommonGrayRuleDao;
import com.kevin.entity.CommonGrayRule;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import io.jmnarloch.spring.cloud.ribbon.support.RibbonFilterContextHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
 
//加入spring的管理
@Component
public class GrayFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return FilterConstants.ROUTE_TYPE;
    }
 
    @Override
    public int filterOrder() {
        return 0;
    }
 
    @Override
    public boolean shouldFilter() {
        //必須返回true,否則過濾器不起作用
        return true;
    }
 
    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    @Autowired
    private CommonGrayRuleDao commonGrayRuleDao;
 
    @Override
    public Object run() throws ZuulException {
        //模擬從數據庫中獲取灰度規則配置,此處根據id獲取的,實際項目中可以從數據庫查處所有放到緩存
        CommonGrayRule commonGrayRule = commonGrayRuleDao.selectByPrimaryKey(1);
 
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        int userId = Integer.parseInt(request.getHeader("userId"));
        //從head中拿出userid,根據數據庫中規則進行匹配,如果灰度規則中有這個用戶就走灰度v1版本,此處模擬的是根據
        //某一個具體的id獲取的值,實際根據情況來定,實際情況中灰度規則也不一定是根據用戶來
        if(commonGrayRule.getId() == userId){
            //核心代碼就這麼一行,實現瞭灰度,這裡的version與要訪問的服務的metadata-map中的key和value進行對應
            RibbonFilterContextHolder.getCurrentContext().add("version","v1");
        }
 
        return null;
    }
}

至此通過網關訪問service-sms服務就可以瞭。如果head中添加version就可以指定到具體服務上。

事前說明:兩個service-sms服務的application.yaml文件如下:

spring:
  profiles: sms1
  application:
    name: service-sms
server:
  port: 8001
eureka:
  client:
    service-url:
      defaultZone: http://eureka-7900:7900/eureka/
  instance:
    metadata-map:
      version: v1
 
 
---
spring:
  profiles: sms2
  application:
    name: service-sms
server:
  port: 8002
eureka:
  client:
    service-url:
      defaultZone: http://eureka-7900:7900/eureka/
  instance:
    metadata-map:
      version: v2

因為本機測試,所以使用的是profiles進行區分。

可以看到一個metadata-map設置的是version: v1 ,另一個是version: v2。

當我們數據庫添加一條用戶id是1的數據時,我們通過網關訪問服務的時候,head裡面添加userId為1的內容,那麼這個用戶為1的請求就會一直走sms1這個服務,否則會在sms1和sms2中輪詢切換。

以上就是淺談Spring Cloud Netflix-Ribbon灰度方案之Zuul網關灰度的詳細內容,更多關於Ribbon灰度方案之Zuul網關灰度的資料請關註WalkonNet其它相關文章!