-
Notifications
You must be signed in to change notification settings - Fork 34
Moon模块使用
Yizzuide edited this page Mar 30, 2020
·
3 revisions
2.2.0+
Moon模块是基于Spring Data Redis的封装,依赖于Light模块的缓存,用于实现环形分配,包含以下分配策略:
- PeriodicMoonStrategy: 周期性对阶段值列表轮询
- PercentMoonStrategy: 百分比轮询
使用业务场景有:
- 短信平台失败时,多个短信平台环形发送(PeriodicMoonStrategy)
- A/B测试用户分配(PercentMoonStrategy)
- 实例权重分配(PercentMoonStrategy)
当前文档使用的版本为3.0.0,使用以下坐标安装:
<dependency>
<groupId>com.github.yizzuide</groupId>
<artifactId>milkomeda-spring-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
<!-- redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
@Configuration
public class MoonConfig {
@Bean("smsMoon")
public Moon<String> smsMoon() {
Moon<String> moon = new Moon<>();
moon.add("七牛云短信", "阿里云短信", "容联云短信");
return moon;
}
@Bean("abTestMoon")
public Moon<Integer> abTestMoon() {
Moon<Integer> moon = new Moon<>();
// 设置缓存缓存实例名(需要在milkomeda.light.instances下配置不同的缓存实例)
moon.setCacheName("ab-test");
PercentMoonStrategy moonStrategy = new PercentMoonStrategy();
moon.setMoonStrategy(moonStrategy);
// AB测试阶段值:15%为0,85%为1
// moon.add(PercentMoonStrategy.parse("15/85"));
// 设置百分比总量(默认为100)
moonStrategy.setPercent(10);
moon.add(PercentMoonStrategy.parse("3/7"));
return moon;
}
}
- 使用
@RestController
@RequestMapping("/moon")
public class MoonController {
@Resource
private Moon<String> smsMoon;
@Resource
private Moon<Integer> abTestMoon;
@RequestMapping("sms")
public String sms() {
return Moon.getPhase("sms-123", smsMoon);
}
@RequestMapping("abTest")
public Integer abTest() {
return Moon.getPhase("ab-123", abTestMoon);
}
}
@EnableMoon
@SpringBootApplication
public class MilkomedaDemoApplication {
public static void main(String[] args) {
SpringApplication.run(MilkomedaDemoApplication.class, args);
}
}
milkomeda:
moon:
instances:
-
name: smsMoon
phases: ["七牛云短信", "阿里云短信", "容联云短信"]
-
name: abTestMoon
cacheName: ab-test
# 使用百分比分配策略
moonStrategyClazz: com.github.yizzuide.milkomeda.moon.PercentMoonStrategy
# 20%的0,80%的1
# phases: [20, 80]
# 缩小总占百分比,使分配更均匀
percent: 10
phases: [2, 8]
- 使用
@RestController
@RequestMapping("/moon")
public class MoonController {
// 动态注册的bean,需要添加@Lazy
@Lazy
@Resource
private Moon<String> smsMoon;
@Lazy
@Resource
private Moon<Integer> abTestMoon;
@RequestMapping("sms")
public String sms() {
return Moon.getPhase("sms-123", smsMoon);
}
@RequestMapping("abTest")
public Integer abTest() {
return Moon.getPhase("ab-123", abTestMoon);
}
}