新增redis viplevel重置脚本

This commit is contained in:
tianfeng 2026-03-17 16:06:33 +08:00
parent 425525f532
commit 8388db8f8e

View File

@ -0,0 +1,55 @@
import com.red.circle.OtherServiceApplication;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.concurrent.TimeUnit;
@SpringBootTest(classes = OtherServiceApplication.class)
@RunWith(SpringRunner.class)
@Slf4j
public class ResetVipLevelTest {
@Autowired
private RedisTemplate redisTemplate;
private static final String VIP_LEVEL_KEY_PATTERN = "GAME:VIP:LEVEL:*";
private static final long EXPIRE_DAYS = 7;
/**
* 批量将所有用户 VIP 等级缓存重置为 0TTL 设置为 7
*/
@Test
public void resetAllVipLevelToZero() {
ScanOptions options = ScanOptions.scanOptions()
.match(VIP_LEVEL_KEY_PATTERN)
.count(500)
.build();
int[] count = {0};
redisTemplate.execute((RedisCallback<Object>) connection -> {
Cursor<byte[]> cursor = connection.scan(options);
while (cursor.hasNext()) {
String key = new String(cursor.next());
redisTemplate.opsForValue().set(key, 0, EXPIRE_DAYS, TimeUnit.DAYS);
count[0]++;
if (count[0] % 100 == 0) {
log.info("已处理: {} 条", count[0]);
}
}
cursor.close();
return null;
});
log.info("完成,共重置 {} 个用户 VIP 缓存 -> 0TTL={}天", count[0], EXPIRE_DAYS);
}
}