一.操作列表类型的数据
package com.sky.test;import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.*;import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;@SpringBootTest
public class SpringDataRedisTest {@Autowiredprivate RedisTemplate redisTemplate;@Testpublic void testRedisTemplate() {System.out.println(redisTemplate); // 首先输出redisTemplate对象看是否为空ValueOperations valueOperations = redisTemplate.opsForValue(); // redis当中的字符串类型数据操作对象HashOperations hashOperations = redisTemplate.opsForHash(); // redis当中的哈希类型数据操作对象ListOperations listOperations = redisTemplate.opsForList(); // redis当中的列表类型数据操作对象SetOperations setOperations = redisTemplate.opsForSet(); // redis当中的集合类型数据操作对象ZSetOperations zSetOperations = redisTemplate.opsForZSet(); // redis当中的有序集合类型数据操作对象}/*操作字符串类型的数据*/@Testpublic void testString() {// set get setex setnxredisTemplate.opsForValue().set("city","北京"); // setString city = (String) redisTemplate.opsForValue().get("city");// getSystem.out.println(city);redisTemplate.opsForValue().set("code","1234",3, TimeUnit.MINUTES); // setexredisTemplate.opsForValue().setIfAbsent("lock","1"); // setnxredisTemplate.opsForValue().setIfAbsent("lock","2");}/*操作哈希类型的数据*/@Testpublic void testHash() {// hset hget hdel hkeys hvalsHashOperations hashOperations = redisTemplate.opsForHash();hashOperations.put("100","name","Rose"); // put(Object key,Object hashKey,Object value)hashOperations.put("100","age","22"); // 对应hsetString name = (String) hashOperations.get("100", "name"); // 对应hgetSystem.out.println(name);Set keys = hashOperations.keys("100"); // 对应hkeysSystem.out.println(keys);List values = hashOperations.values("100"); // 对应hvalsSystem.out.println(values);hashOperations.delete("100","name"); // 对应hdel}/*操作列表类型的数据*/@Testpublic void testList() {ListOperations listOperations = redisTemplate.opsForList();// leftPushAll(Object key, Object ...values):一次往列表中插入多个元素listOperations.leftPushAll("mylist","a","b","c");// leftPush(Object key, Object value):往列表中插入单个元素listOperations.leftPush("mylist","d");// range(Object key,Long start, Long end):获取列表指定范围内的元素,并构成一个列表List mylist = listOperations.range("mylist", 0, -1);System.out.println(mylist);// rightPop(Object key):移除并获取列表的最后一个元素String rightPop = (String) listOperations.rightPop("mylist");System.out.println(rightPop);// size(Object key):获取列表长度Long length = listOperations.size("mylist");System.out.println(length);}
}
1.leftPushAll(Object key, Object ...values):一次往列表中插入多个元素,对应redis中的LPUSH
[c, b, a]
2.leftPush(Object key, Object value):往列表中插入单个元素,对应redis中的LPUSH
3.range(Object key,Long start, Long end):获取列表指定范围内的元素,并构成一个列表,对应redis中的Lrange
[d, c, b, a]
4.rightPop(Object key):移除并获取列表的最后一个元素,对应redis中的rpop
5.size(Object key):获取列表长度,对应redis中的Llen:4