本文介绍如何利用dubbo自定义负载实现简单灰度(用户纬度,部分用户访问一个服务,其余访问剩余服务)。
其实在这之前,对dubbo了解的也不是很多,只是简单的使用过,跑了几个demo而已,但是得知接下来可能要用dubbo进行开发,还是赶紧补了一下相关的知识,看了看官网,另外买了一本书《深入理解Apache Dubbo实战》,看了一大半,感觉还是很不错的。
1.dubbo负载均衡介绍
因为官网介绍的很详细了,这里只简单的说一下。dubbo负载均衡包含如下四种:
- RandomLoadBalance:默认的负载策略,随机负载。
- ConsistentHashLoadBalance:一致性 Hash负载。
- LeastActiveLoadBalance:最少活跃数负载。
- RoundRobinLoadBalance:轮询负载。
这四个类都继承了AbstractLoadBalance抽象类,源码相关分析可以查看官方:http://dubbo.apache.org/zh-cn/docs/source_code_guide/loadbalance.html
2.springboot-dubbo实现自定义负载方法
springboot-dubbo使用自定义负载其实很简单,大致分为如下几步:
- 1.创建自定义负载类,继承AbstractLoadBalance,重写doSelect方法,这个方法就是定义算法规则的地方。
- 2.添加dubbo负载扩展点,在src/main/resources目录下创建META-INFO/dubbo目录,在目录下创建org.apache.dubbo.rpc.cluster.LoadBalance文件,里面配置对应的负载算法类,如下:
gray=com.dalaoyang.balance.GrayLoadBalance
- 3.配置文件中使用,如下:
dubbo.provider.loadbalance=gray
3.模拟灰度方案及具体实现
3.1 灰度场景
现在模拟一个这样的方案,比如有4个服务提供者,端口分别是9001,9002,9003,9004,将其中9002端口的服务设置为灰度服务,当请求消费者接口testUser的userid为1-10时,强制转发到到灰度状态的提供者去,其余的还是请求到正常的服务,如图所示。
3.2 代码实现
接下来使用代码简单实现如上场景。
3.2.1 服务提供者
首先看一下pom文件,都是一些springboot-dubbo的依赖,如下:
<?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 http://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.0.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.dalaoyang</groupId>
<artifactId>springboot_dubbo_provider</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot_dubbo_provider</name>
<description>springboot_dubbo_provider</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- Aapche Dubbo -->
<dependency>
<groupId>org.apache.dubbo</groupId>
<artifactId>dubbo-spring-boot-starter</artifactId>
<version>2.7.1</version>
</dependency>
<dependency>
<groupId>org.apache.dubbo</groupId>
<artifactId>dubbo</artifactId>
<version>2.7.2</version>
<exclusions>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring</artifactId>
</exclusion>
<exclusion>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
</exclusion>
<exclusion>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-framework</artifactId>
<version>2.8.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.curator/curator-recipes -->
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-recipes</artifactId>
<version>2.8.0</version>
</dependency>
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
<exclusions>
<exclusion>
<artifactId>log4j</artifactId>
<groupId>log4j</groupId>
</exclusion>
<exclusion>
<artifactId>slf4j-log4j12</artifactId>
<groupId>org.slf4j</groupId>
</exclusion>
</exclusions>
<version>3.4.10</version>
<type>pom</type>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
然后暴露一个接口,供服务消费者使用,如下:
package com.dalaoyang.api;
public interface UserService {
String testUser(Long userId, String version);
}
实现类,接口返回对应的端口,dubbo的端口,如下:
package com.dalaoyang.api.impl;
import com.dalaoyang.api.UserService;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Value;
@Service
public class UserServiceImpl implements UserService {
@Value("${server.port}")
private String port;
@Value("${dubbo.protocol.port}")
private String dubboPort;
@Override
public String testUser(Long userId, String version) {
return "调用成功,端口是:" + port +
"。版本号是:" + version +
",用户id:" + userId +
",dubbo端口:" + dubboPort;
}
}
创建一个GrayLoadBalance继承AbstractLoadBalance类,其中包含如下配置:
- 当前请求的userId使用的dubbo隐式传参(也可以选用其他方式)。
- 灰度用户名单配置在了消费者的配置中
- 服务提供者配置中配置了一个属性status用于区分是prod服务还是gray服务。
- 没有匹配对象的话,使用随机负载策略进行分发。
看完上面的简介,在看代码就容易了很多,大致就是取出请求的用户id和灰度用户id集合,判断是否是灰度用户,如果是,则选择灰度服务,如下:
package com.dalaoyang.balance;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.cluster.loadbalance.AbstractLoadBalance;
import org.springframework.stereotype.Component;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
@Component
public class GrayLoadBalance extends AbstractLoadBalance {
public static final String NAME = "gray";
public GrayLoadBalance() {
}
@Override
protected <T> Invoker<T> doSelect(List<Invoker<T>> invokers, URL url, Invocation invocation) {
List<Invoker<T>> list = new ArrayList<>();
for (Invoker invoker : invokers) {
list.add(invoker);
}
Map<String, String> map = invocation.getAttachments();
String userId = map.get("userId");
Iterator<Invoker<T>> iterator = list.iterator();
String grayUserIds = url.getParameter("grayUserids", "");
String[] arrs = grayUserIds.split(",");
while (iterator.hasNext()) {
Invoker<T> invoker = iterator.next();
String providerStatus = invoker.getUrl().getParameter("status", "prod");
if (Objects.equals(providerStatus, NAME)) {
if (Arrays.asList(arrs).contains(userId)) {
return invoker;
} else {
iterator.remove();
}
}
}
return this.randomSelect(list, url, invocation);
}
/**
* 重写了一遍随机负载策略
*
* @param invokers
* @param url
* @param invocation
* @param <T>
* @return
*/
private <T> Invoker<T> randomSelect(List<Invoker<T>> invokers, URL url, Invocation invocation) {
int length = invokers.size();
boolean sameWeight = true;
int[] weights = new int[length];
int firstWeight = this.getWeight((Invoker) invokers.get(0), invocation);
weights[0] = firstWeight;
int totalWeight = firstWeight;
int offset;
int i;
for (offset = 1; offset < length; ++offset) {
i = this.getWeight((Invoker) invokers.get(offset), invocation);
weights[offset] = i;
totalWeight += i;
if (sameWeight && i != firstWeight) {
sameWeight = false;
}
}
if (totalWeight > 0 && !sameWeight) {
offset = ThreadLocalRandom.current().nextInt(totalWeight);
for (i = 0; i < length; ++i) {
offset -= weights[i];
if (offset < 0) {
return (Invoker) invokers.get(i);
}
}
}
return (Invoker) invokers.get(ThreadLocalRandom.current().nextInt(length));
}
}
接下来在src/main/resources/META-INF/dubbo下添加org.apache.dubbo.rpc.cluster.LoadBalance新增扩展点,内容如下:
gray=com.dalaoyang.balance.GrayLoadBalance
这里使用了多配置文件来启动多个服务提供者,主配置文件application.properties内容如下:
spring.profiles.active=test3
dubbo.provider.loadbalance=gray
application-test1.properties内容如下:
##端口号
server.port=9001
## Dubbo配置
dubbo.application.name=dubbo_provider
dubbo.registry.address=zookeeper://127.0.0.1:2181
dubbo.protocol.name=dubbo
dubbo.protocol.port=9011
dubbo.scan.base-packages=com.dalaoyang
dubbo.provider.version=2.0.0
application-test2.properties内容如下,这里多配置了dubbo.provider.parameters.status=gray属性用于区分灰度服务:
##端口号
server.port=9002
## Dubbo配置
dubbo.application.name=dubbo_provider
dubbo.registry.address=zookeeper://127.0.0.1:2181
dubbo.protocol.name=dubbo
dubbo.protocol.port=9012
dubbo.scan.base-packages=com.dalaoyang
dubbo.provider.version=2.0.0
dubbo.provider.parameters.status=gray
application-test3.properties内容如下:
##端口号
server.port=9003
## Dubbo配置
dubbo.application.name=dubbo_provider
dubbo.registry.address=zookeeper://127.0.0.1:2181
dubbo.protocol.name=dubbo
dubbo.protocol.port=9013
dubbo.scan.base-packages=com.dalaoyang
dubbo.provider.version=2.0.0
application-test4.properties内容如下:
##端口号
server.port=9004
## Dubbo配置
dubbo.application.name=dubbo_provider
dubbo.registry.address=zookeeper://127.0.0.1:2181
dubbo.protocol.name=dubbo
dubbo.protocol.port=9014
dubbo.scan.base-packages=com.dalaoyang
dubbo.provider.version=2.0.0
到这里,服务提供者就创建完成了。
3.2.2 服务消费者
服务消费者就简单很多,pom文件除dubbo对应包以外,引入服务提供者的包,如下:
<?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 http://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.0.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.dalaoyang</groupId>
<artifactId>springboot_dubbo_consumer</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot_dubbo_consumer</name>
<description>springboot_dubbo_consumer</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- Aapche Dubbo -->
<dependency>
<groupId>org.apache.dubbo</groupId>
<artifactId>dubbo-spring-boot-starter</artifactId>
<version>2.7.1</version>
</dependency>
<dependency>
<groupId>org.apache.dubbo</groupId>
<artifactId>dubbo</artifactId>
<version>2.7.2</version>
<exclusions>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring</artifactId>
</exclusion>
<exclusion>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
</exclusion>
<exclusion>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.dalaoyang</groupId>
<artifactId>springboot_dubbo_provider</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-framework</artifactId>
<version>2.8.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.curator/curator-recipes -->
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-recipes</artifactId>
<version>2.8.0</version>
</dependency>
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
<exclusions>
<exclusion>
<artifactId>log4j</artifactId>
<groupId>log4j</groupId>
</exclusion>
<exclusion>
<artifactId>slf4j-log4j12</artifactId>
<groupId>org.slf4j</groupId>
</exclusion>
</exclusions>
<version>3.4.10</version>
<type>pom</type>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
配置文件中配置上述需要的灰度userid名单,如下:
## 端口号
server.port=8881
##Dubbo配置
dubbo.application.name=dubbo_consumer
dubbo.registry.address=zookeeper://localhost:2181
dubbo.scan.base-packages=com.dalaoyang.api
dubbo.consumer.version=2.0.0
dubbo.consumer.parameters.grayUserids=1,2,3,4,5,6,7,8,9,10
dubbo.provider.loadbalance=gray
dubbo.protocol.port=10000
创建一个TestController,编写一个简单的测试类,调用dubbo服务,内容如下:
package com.dalaoyang.controller;
import com.dalaoyang.api.UserService;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.rpc.RpcContext;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Objects;
@RestController
public class TestController {
@Reference
private UserService userService;
//灰度用户 http://localhost:8881/testUser?userId=3333&version=2.0.0
//正常用户 http://localhost:8881/testUser?userId=10&version=2.0.0
@GetMapping("/testUser")
public String testUser(Long userId, String version) {
RpcContext.getContext().setAttachment("userId", Objects.nonNull(userId) ? userId.toString() : "");
return userService.testUser(userId, version);
}
}
服务消费者到这里也完成了。
4.测试
4.1 启动项目
- 1.启动zookeeper
- 2.启动服务提供者,可以使用idea启动多服务,也可以打包,分别制定不同配置文件启动,任何方式都可以。
- 3.服务提供者启动完成后,启动服务消费者。
4.2 页面请求
如果灰度状态的服务启动的话,访问http://localhost:8881/testUser?userId=10&version=2.0.0,如图所示。
如果灰度状态的服务没有启动,或者userid不在1-10之间的话会显示如下图所示。
5.源码
本文相关源码全部上传到了码云上,地址是https://gitee.com/dalaoyang/springboot_dubbo