令牌桶限流

引入redis的maven依赖

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<version>2.6.6</version>
</dependency>

增加config配置

@Configuration
public class RedisConfig {

@Bean
public RedisTemplate<String,Object> redisTemplate(LettuceConnectionFactory lettuceConnectionFactory) {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(lettuceConnectionFactory);
redisTemplate.setKeySerializer(RedisSerializer.string());
redisTemplate.setValueSerializer(RedisSerializer.string());
return redisTemplate;
}
}

设置定时任务以固定时间增加令牌桶数量,decr接口是处理业务消费令牌的

@Slf4j
@EnableScheduling
@RestController
public class RedisController {

@Autowired
private RedisTemplate<String,Object> redisTemplate;

@GetMapping("/decr")
public void decr(){
Object list = redisTemplate.opsForList().leftPop("list");
if(list == null){
log.info("系统繁忙,请稍后重试!");
return;
}
log.info("可以进入处理业务 {}",list);
}

@Scheduled(cron = "1/5 * * * * ?")
public void incr(){
Long list = redisTemplate.opsForList().size("list");
log.info("令牌桶数量为 :{}",list);
if (list == null || list < 20) {
for (int i = 0; i < 10; i++) {
redisTemplate.opsForList().leftPush("list", UUID.randomUUID().toString());
}
}
}
}