| 知乎专栏 |
ListOperations
public class Example {
// inject the actual template
@Autowired
private RedisTemplate<String, String> template;
// inject the template as ListOperations
// can also inject as Value, Set, ZSet, and HashOperations
@Resource(name="redisTemplate")
private ListOperations<String, String> listOps;
public void addLink(String userId, URL url) {
listOps.leftPush(userId, url.toExternalForm());
// or use template directly
redisTemplate.boundListOps(userId).leftPush(url.toExternalForm());
}
}
ListOperations<String, Object> list = redisTemplate.opsForList();
list.rightPush("books", "Linux");
list.rightPush("books", "Java");
System.out.println(list.range("books", 0, 1));
System.out.println(redisTemplate.opsForList().size("list"));
String[] stringarrays = new String[]{"1","2","3"};
redisTemplate.opsForList().rightPushAll("listarrayright",stringarrays);
System.out.println(redisTemplate.opsForList().range("listarrayright",0,-1));
List<Object> strings = new ArrayList<Object>();
strings.add("1");
strings.add("2");
strings.add("3");
redisTemplate.opsForList().rightPushAll("listcollectionright", strings);
System.out.println(redisTemplate.opsForList().range("listcollectionright",0,-1));
System.out.println("========== KEY 不存在===========");
System.out.println(redisTemplate.opsForList().rightPushIfPresent("rightPushIfPresent","aa"));
System.out.println(redisTemplate.opsForList().rightPushIfPresent("rightPushIfPresent","bb"));
System.out.println("========== KEY 已经存在===========");
System.out.println(redisTemplate.opsForList().rightPushIfPresent("rightPushIfPresent","aa"));
System.out.println(redisTemplate.opsForList().rightPushIfPresent("rightPushIfPresent","bb"));
@Autowired
private RedisTemplate<String, String> template;
// 将模板作为 ListOperations 注入
@Resource(name="redisTemplate")
private ListOperations<String, String> listOps;
public void addLink(String userId, URL url) {
listOps.leftPush(userId, url.toExternalForm());
}
redisTemplate.opsForList().leftPush("list","java");
redisTemplate.opsForList().leftPush("list","python");
redisTemplate.opsForList().leftPush("list","c++");
批量把一个数组插入到列表中
String[] stringarrays = new String[]{"1","2","3"};
redisTemplate.opsForList().leftPushAll("listarray",stringarrays);
批量把一个集合插入到列表中
使用:List<Object> strings = new ArrayList<Object>();
strings.add("1");
strings.add("2");
strings.add("3");
redisTemplate.opsForList().leftPushAll("listcollection", strings);
System.out.println(redisTemplate.opsForList().range("listcollection",0,-1));
结果:[3, 2, 1]