package com.ydtech.modules.ttqf.xxx; import org.springframework.data.redis.core.RedisCallback; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.ValueOperations; import org.springframework.data.redis.core.script.DefaultRedisScript; import org.springframework.stereotype.Service; import java.util.Arrays; import java.util.Collections; import java.util.List; @Service public class RoundRobinService { private final RedisTemplate redisTemplate; public static final String LIST_KEY = "DEFAULT:WITHDRAWAL:id"; private static final String INDEX_KEY = "DEFAULT:WITHDRAWAL:index"; public RoundRobinService(RedisTemplate redisTemplate) { this.redisTemplate = redisTemplate; } private static final String LUA_SCRIPT = "local indexKey = KEYS[2] " + "local listKey = KEYS[1] " + "local currentIndex = tonumber(redis.call('GET', indexKey) or 0) " + "local listSize = redis.call('LLEN', listKey) " + "if listSize == 0 then return nil end " + "local value = redis.call('LINDEX', listKey, currentIndex) " + "local nextIndex = (currentIndex + 1) % listSize " + "redis.call('SET', indexKey, nextIndex) " + "return value"; public String getNextWithLua() { DefaultRedisScript script = new DefaultRedisScript<>(LUA_SCRIPT, String.class); return redisTemplate.execute(script, Arrays.asList(LIST_KEY, INDEX_KEY)); } // 添加成员(动态扩展) public void batchAdd(List values) { Long l = redisTemplate.opsForList().rightPushAll(LIST_KEY, values); System.out.println("添加成功,当前队列长度为:" + l); } public boolean remove(String value) { String script = "local list = redis.call('LRANGE', KEYS[1], 0, -1) " + "local new_list = {} " + "for i, v in ipairs(list) do " + " if v ~= ARGV[1] then " + " table.insert(new_list, v) " + " end " + "end " + "redis.call('DEL', KEYS[1]) " + "redis.call('RPUSH', KEYS[1], unpack(new_list)) " + "return #new_list"; Long result = redisTemplate.execute( new DefaultRedisScript<>(script, Long.class), Collections.singletonList(LIST_KEY), value ); return result != null && result > 0; } /** * 添加字符串到集合 */ public void addString(String item) { redisTemplate.opsForList().rightPush(LIST_KEY, item); } }