RedisTemlale操作List测试类

本文详细介绍如何使用Java操作Redis中的列表数据结构,包括批量插入、获取指定范围的数据、删除指定值等常见操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath*:/applicationContext-test.xml" })
public class RestListTest extends UnitilsJUnit4 {

@Resource(name = "redisTemplate")
private ListOperations<String, Long> opsForList;
@Autowired
private RedisCacheUtil redisCacheUtil;

@Test
public void test1() {
// 问题下的回答id列表;
List<Long> answerIdsByQuestion = new ArrayList<>();
String key = "test_questionId" + 3;
redisCacheUtil.delete(key);
List list2 = new ArrayList();// 注意这里虽然是Long类型但是不能用泛型标注为Long,不然会报错;
list2.add(11L);
list2.add(12L);
list2.add(13L);
list2.add(14L);
list2.add(17L);
list2.add(15L);
list2.add(16L);
list2.add(17L);
list2.add(18L);
list2.add(17L);
list2.add(19L);
opsForList.rightPushAll(key, list2);// 批量添加;
opsForList.leftPush(key, 9L);// 左边添加一位元素;
opsForList.rightPush(key, 21L);// 列表的右边添加1位元素
List<Long> range1 = opsForList.range(key, 0, -1);// 0,-1获取所有的元素,可以用来做分页;
Long aLong1 = opsForList.leftPop(key);// 弹出左边的元素,(获取并移除)
List<Long> range2 = opsForList.range(key, 0, -1);
Long aLong2 = opsForList.rightPop(key);// 弹出右边的元素,(获取并移除)
List<Long> range3 = opsForList.range(key, 0, -1);
Long remove1 = opsForList.remove(key, 1, 16L);// 移除从左到右第一个值为16的元素
Long remove2 = opsForList.remove(key, 2, 17L);// 移除从左到右两个值为17的元素
Long index = opsForList.index(key, 2);//获取索引为2的元素
Long size = opsForList.size(key);
// 获取分页数据 第2,每页3条数据
int pageNo = 2;
int pageSize = 3;
List<Long> range4 = opsForList.range(key, (pageNo - 1) * pageSize, (pageNo * pageSize) - 1);

List<Long> range5 = opsForList.range(key, 0, -1);
opsForList.trim(key,3,5);//移除索引3-5以外的所有元素;
List<Long> range6 = opsForList.range(key, 0, -1);
}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值