0%

redis之Template

Spring操作redis和java操作redis(也就是jedis)有所不同,通常有三种,第一个是RedisTemplate,第二个是StringRedisTemplate,第三是bound api,

1.RedisTemplate

​ 在RedisTemplate中,对k-v都是有要求的,key和value本身都是JdkSerializationRedisSerializer的序列化,而key默认是String类型,value本身就是Object对象,所以只需要重新设置key的序列化方法,使用StringRedisSerializer就可以了,案例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package cn.zl.springbootredis.redis;

import cn.zl.springbootredis.SpringbootRedisApplication;
import cn.zl.springbootredis.entity.User;
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.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.UUID;

/**
* @Description:
* @Author: zl
* @Date: 2020/9/7 13:24
*/
//启动Springboot应用
@SpringBootTest(classes = SpringbootRedisApplication.class)
@RunWith(SpringRunner.class)
public class TestRedisTemplate {
@Autowired
private RedisTemplate redisTemplate;//key Object value Object ====>对象序列化

//opsForxxx Vlaue String List Set Zset hash

@Test
public void testRedisTemplate(){
//修改key序列化方案 String类型序列
redisTemplate.setKeySerializer(new StringRedisSerializer());

//修改hash key的序列化方案
redisTemplate.setHashKeySerializer(new StringRedisSerializer());

User user = new User();
user.setId(Long.valueOf(UUID.randomUUID().toString())).setName("小陈").setAge(23).setEmail("zllwsy@outlook.com");
redisTemplate.opsForValue().set("user",user);//redis进行设置 对象需要经过序列化
User user1 = (User) redisTemplate.opsForValue().get("user");
System.out.println(user1);

redisTemplate.opsForList().leftPush("list",user);

redisTemplate.opsForSet().add("set",user);

redisTemplate.opsForZSet().add("zset",user,10);

redisTemplate.opsForHash().put("map","name",user);
}
}

2.StringRedisTemplate

​ StringRedisTemplate意思很明了,key和value都是String类型,下面是一些常见操作,案例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package cn.zl.springbootredis.redis;

import cn.zl.springbootredis.SpringbootRedisApplication;
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.connection.DataType;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
* @Description:
* @Author: zl
* @Date: 2020/9/7 11:08
*/
//启动Springboot应用
@SpringBootTest(classes = SpringbootRedisApplication.class)
@RunWith(SpringRunner.class)
public class TestStringRedisTemplate {
@Autowired
private StringRedisTemplate stringRedisTemplate;//key ,value都是字符串

//操作redis中key相关
@Test
public void testKey(){
// stringRedisTemplate.delete("name");//删除一个key
Boolean hasKey = stringRedisTemplate.hasKey("name");//判断某个key是否存在
System.out.println(hasKey);
DataType name = stringRedisTemplate.type("name");//判断key所对应值的类型
System.out.println(name);
Set<String> keys = stringRedisTemplate.keys("*");//获取redis中所有
keys.forEach(key -> System.out.println("key = "+ key));
Long expire = stringRedisTemplate.getExpire("name");//获取key的超时时间
System.out.println(expire);//-1,代表永不超时;-2 key不存在,>=0 超时时间
stringRedisTemplate.randomKey();//所及获取一个key
stringRedisTemplate.rename("age","age1");//修改key的名字,要求key必须存在,不存在会报错
stringRedisTemplate.renameIfAbsent("age","age1");//也是修改key的名字,但是会判断key是否存在
stringRedisTemplate.move("name",1);//移动key到指定库
}

//操作redis中字符串,opsForValue实际就是操作redis中的String类型
@Test
public void testString(){
stringRedisTemplate.opsForValue().set("name","小张");//设置 key value
String name = stringRedisTemplate.opsForValue().get("name");//获取value
System.out.println(name);
stringRedisTemplate.opsForValue().set("code","2357",60, TimeUnit.SECONDS);//设置一个key的超时时间
stringRedisTemplate.opsForValue().append("name","你是个好人");//追加
}
//操作redis中list类型,opsForList实际就是操作redis中list类型
@Test
public void testList(){
stringRedisTemplate.opsForList().leftPush("names","小黑");//创建一个列表,并放入一个元素
stringRedisTemplate.opsForList().leftPushAll("names","小花","小王","小明");
ArrayList<Object> names = new ArrayList<>();
names.add("xiaoming");
names.add("xiaosan");
stringRedisTemplate.opsForList().leftPushAll("names", String.valueOf(names));//创建一个列表,放入多个元素
List<String> stringList = stringRedisTemplate.opsForList().range("names", 0, -1);//遍历list
stringList.forEach( value -> System.out.println("value = "+ value));
stringRedisTemplate.opsForList().trim("names",1,3);//截取指定区间的list,前三个,
}

//操作redis中set类型,opsForSet实际就是操作redis中set类型
@Test
public void testSet(){
stringRedisTemplate.opsForSet().add("sets","张三","李三","xiaoming");//添加
Set<String> sets = stringRedisTemplate.opsForSet().members("sets");//成员
sets.forEach( value -> System.out.println("value = " +value));

stringRedisTemplate.opsForSet().size("sets");//获取set集合元素个数
}
//操作redis中zset类型,opsForZSet实际就是操作redis中zset类型
@Test
public void testZset(){
stringRedisTemplate.opsForZSet().add("zsets","张三",100);//创建并放入元素
Set<String> zsets = stringRedisTemplate.opsForZSet().range("zsets", 1, -1);//指定范围查询
zsets.forEach( value -> System.out.println("value = "+value));
Set<ZSetOperations.TypedTuple<String>> zsets1 = stringRedisTemplate.opsForZSet().rangeByScoreWithScores("zsets", 0, 100);
zsets1.forEach( typedTuple-> {
System.out.println(typedTuple.getValue());
System.out.println(typedTuple.getScore());
});
}
//操作redis中Hash类型,opsForHash实际就是操作redis中Hash类型
@Test
public void testHash(){
stringRedisTemplate.opsForHash().put("maps","name","张三");//创建一个hash类型,并放入key value
HashMap<String, String> map = new HashMap<>();
map.put("age","12");
map.put("bir","2020-2-2");
stringRedisTemplate.opsForHash().putAll("maps",map);//放入多个key value

List<Object> values = stringRedisTemplate.opsForHash().multiGet("maps", Arrays.asList("name", "age"));//获取多个key
String value = (String) stringRedisTemplate.opsForHash().get("maps","name");//获取hash中某个key的值
List<Object> vals = stringRedisTemplate.opsForHash().values("maps");//获取所有values
Set<Object> keys = stringRedisTemplate.opsForHash().keys("maps");//获取所有key
}

}

3.Bound Api

​ bound api其实就是一种简化操作,是由Spring data 为了方便对redis进行更友好的操作而提供的,案例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package cn.zl.springbootredis.redis;

import cn.zl.springbootredis.SpringbootRedisApplication;
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.BoundListOperations;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.List;

/**
* @Description:
* @Author: zl
* @Date: 2020/9/7 13:51
*/
//启动Springboot应用
@SpringBootTest(classes = SpringbootRedisApplication.class)
@RunWith(SpringRunner.class)
public class TestBoundAPI {
@Autowired
private RedisTemplate redisTemplate;
@Autowired
private StringRedisTemplate stringRedisTemplate;

@Test
public void testBound(){
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setHashKeySerializer(new StringRedisSerializer());

stringRedisTemplate.opsForValue().set("name","Diamond");
stringRedisTemplate.opsForValue().append("name","你是一个好人");
String s = stringRedisTemplate.opsForValue().get("name");
System.out.println(s);

//如果确认是对一个key多次操作,则对key进行绑定
//滴哦字符串类型key进行绑定 后续所有操作都是基于这个key的操作,后续的操作参数就少了key的值
BoundValueOperations<String, String> nameValue = stringRedisTemplate.boundValueOps("name");
nameValue.set("Diamond");
nameValue.append("你是一个好人");
String s1 = nameValue.get();
System.out.println(s1);

//对list set zset hash

BoundListOperations<String, String> listsValue = stringRedisTemplate.boundListOps("lists");
listsValue.leftPushAll("张三","李四","王五");
List<String> range = listsValue.range(0, -1);
range.forEach( value -> System.out.println(value));

//set
// stringRedisTemplate.boundSetOps();
//zset
// stringRedisTemplate.boundZSetOps();
//hash
// stringRedisTemplate.boundHashOps();
/**
* 1.针对日后处理key value 都是String 使用StringRedisTemplate
* 2.针对日后处理key value 存在对象 使用RedisTemplate
* 3.针对同一个key多次操作可以使用boundXXXops()的api,简化书写
*/
}

}

----------本文结束感谢您的阅读----------