一.操作列表类型的数据
java
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 {
@Autowired
private RedisTemplate redisTemplate;
@Test
public 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当中的有序集合类型数据操作对象
}
/*
操作字符串类型的数据
*/
@Test
public void testString() {
// set get setex setnx
redisTemplate.opsForValue().set("city","北京"); // set
String city = (String) redisTemplate.opsForValue().get("city");// get
System.out.println(city);
redisTemplate.opsForValue().set("code","1234",3, TimeUnit.MINUTES); // setex
redisTemplate.opsForValue().setIfAbsent("lock","1"); // setnx
redisTemplate.opsForValue().setIfAbsent("lock","2");
}
/*
操作哈希类型的数据
*/
@Test
public void testHash() {
// hset hget hdel hkeys hvals
HashOperations hashOperations = redisTemplate.opsForHash();
hashOperations.put("100","name","Rose"); // put(Object key,Object hashKey,Object value)
hashOperations.put("100","age","22"); // 对应hset
String name = (String) hashOperations.get("100", "name"); // 对应hget
System.out.println(name);
Set keys = hashOperations.keys("100"); // 对应hkeys
System.out.println(keys);
List values = hashOperations.values("100"); // 对应hvals
System.out.println(values);
hashOperations.delete("100","name"); // 对应hdel
}
/*
操作列表类型的数据
*/
@Test
public 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);
}
}