簡述
上一文中簡述了使用StringRedisTemplate操作redis中的string類型茫陆,今天來記錄一下操作list類型的主要方法
代碼
使用springboot的單元測試進行演示
package com.bpf.RedisTempletDemo.list;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
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.StringRedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class ListDemo {
@Autowired
private StringRedisTemplate redisTemplate;
@Test
public void demo1() {
//從左邊插入,即插入到列表頭部
redisTemplate.opsForList().leftPush("product:list", "iphone xs max");
redisTemplate.opsForList().leftPush("product:list", "thinkpad x1 carbon");
redisTemplate.opsForList().leftPush("product:list", "mackBook pro13");
redisTemplate.opsForList().leftPush("product:list", "HuaWei Mate20 pro");
}
@Test
public void demo2() {
//從左邊插入一個數(shù)組
String[] books = new String[] {"java編程思想", "springboot從入門到精通"};
redisTemplate.opsForList().leftPushAll("book:list", books);
}
@Test
public void demo3() {
//從左邊插入一個集合
List<String> list = new ArrayList<String>();
list.add("鬼泣5");
list.add("荒野大鏢客2");
list.add("仙劍奇?zhèn)b傳7");
redisTemplate.opsForList().leftPushAll("game:list", list);
}
@Test
public void demo4() {
//如果存在key對應的列表拖叙,則從左插入诅炉,不存在不做操作
redisTemplate.opsForList().leftPushIfPresent("fruit:list", "1");
}
@Test
public void demo5() {
//在key對應的列表中從左邊開始找蜡歹,找到第一個pivot,然后把value插到pivot左邊涕烧,沒有不做操作
redisTemplate.opsForList().leftPush("product:list", "HuaWei Mate20X", "xiaomi mix");
}
//也可以從右邊插入月而,把上面的left改為right即可
@Test
public void demo6() {
//指定位置重新設置指定值
redisTemplate.opsForList().set("product:list", 1, "dell xps13");
}
@Test
public void demo7() {
//刪除和value相同的count個元素,count < 0议纯,從右開始,count > 0父款,從左開始,count = 0,全部
redisTemplate.opsForList().remove("product:list", -1, "HuaWei Mate20 pro");
}
@Test
public void demo8() {
//獲取制定下標對應的值 index,從0開始瞻凤,有正負兩套下標
//[a,b,c,d] 下標有[0,1,2,3]和[0,-3,-2,-1];
String value = redisTemplate.opsForList().index("product:list", 1);
System.out.println(value);
}
@Test
public void demo9() {
//查詢list中指定范圍的內(nèi)容
List<String> list = redisTemplate.opsForList().range("product:list", 0, -1);
System.out.println(list);
//修剪列表憨攒,使其只包含指定范圍內(nèi)的元素
redisTemplate.opsForList().trim("product:list", 0, 2);
//查詢列表長度
System.out.println(redisTemplate.opsForList().size("product:list"));
}
@Test
public void demo10() {
//彈出最左邊元素
redisTemplate.opsForList().leftPop("product:list");
//移出并獲取列表的第一個元素, 如果列表沒有元素會阻塞列表直到等待超時阀参。
redisTemplate.opsForList().leftPop("k1", 10, TimeUnit.SECONDS);
//彈出最右邊元素
redisTemplate.opsForList().rightPop("product:list");
//彈出k1最右邊元素并放入k2最左邊
redisTemplate.opsForList().rightPopAndLeftPush("product:list", "game:list");
}
}