springboot redis存储分布式轮询算法下标 轮询获取yml的list元素

pom.xml

        <!--        配置注释处理器 @ConfigurationProperties yml使用list@Value获取会报错-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>

application.yml

pass-uri:
  not-check:
    - hello
    - getVCode
    - checkUserId
    - front
    - login
    - fileUpload
    - fileDelete
    - roundRobin

NotCheckConfig.java

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import java.util.List;

@Data
@Configuration
@ConfigurationProperties(prefix = "pass-uri") // yml配置文件的前缀
public class NotCheckConfig {
    private List<String> notCheck;//yml list变量名(建议和yml配置的名称一致)
}

轮询调用
RoundRobinController.java

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

@RestController
public class RoundRobinController {
    @Resource
    private NotCheckConfig notCheckConfig;

    @Resource
    private RedisTemplate<String, Integer> redisTemplate;

    /**
     * 轮询获取yml配置的list
     * @return
     */
    @GetMapping("roundRobin")
    public String roundRobin() {
        String INDEX = "index";
        if (!redisTemplate.hasKey(INDEX)) redisTemplate.opsForValue().set(INDEX, 0);//如果key不存在就创建key,并设置下标初始值为0
        int index = redisTemplate.opsForValue().get(INDEX);//有下标则直接获取
        List<String> list = notCheckConfig.getNotCheck();//获取yml配置的集合
        if (index >= list.size()) index = 0;//超过list集合的值就重新赋值(轮询)
        String ip = list.get(index);//获取集合中第index个元素的值,每次调用获取list中的第index条数据
        redisTemplate.opsForValue().set(INDEX, ++index);//利用redis单线程的特性存放全局index下标
        return ip;
    }
}

每访问一次获取其中的一条数据
在这里插入图片描述
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值