SpringDataRedis操作Redis五种数据类型添加依赖
<!-- Redis 依赖 -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.1</version>
</dependency>
<!-- spring data redis 依赖使⽤ 1+最新版本因为 2+需要 spring5+版本 -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.8.18.RELEASE</version>
</dependency>
添加 l 配置⽂件
<!-- 连接池配置 -->
<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
<!-- 最⼤连接数 -->
<property name="maxTotal" value="1024"/>
<!-- 最⼤空闲连接数 -->
<property name="maxIdle" value="200"/>
<!-- 获取连接时最⼤等待毫秒数 -->
<property name="maxWaitMillis" value="10000"/>
<!-- 在获取连接时检查有效性 -->
<property name="testOnBorrow" value="true"/>
</bean>
<!-- 客户端连接⼯⼚ -->
<bean id="jedisConnFactory" class="org.tion.jedis.JedisConnectionFactory"
p:use-pool="true" p:host-name="192.168.75.163" p:port="6379" >
<!-- 连接池引⽤ -->
<constructor-arg name="poolConfig" ref="jedisPoolConfig"/>
</bean>
<!-- redisTemplate 配置 -->
<bean id="redisTemplate" class="org.RedisTemplate"
p:connection-factory-ref="jedisConnFactory">
<!-- 配置序列化操作 -->
<property name="keySerializer">
<bean class="org.dis.serializer.StringRedisSerializer"/>
</property>
<property name="valueSerializer">
<bean class="org.dis.serializer.StringRedisSerializer"/>
</property>
<property name="hashKeySerializer">
<bean class="org.dis.serializer.StringRedisSerializer"/>
</property>
<property name="hashValueSerializer">
<bean class="org.dis.serializer.StringRedisSerializer"/>
</property>
redis支持的五种数据类型</bean>
测试环境是否搭建成功
4.1、操作 String
@Autowired
private RedisTemplate<String, Object> redisTemplate;
/**
* redisTemplate.opsForValue() -> ValueOperations<String, Object>;// 操作字符串
* redisTemplate.opsForHash() -> HashOperations<String, String, String>;// 操作 hash
* redisTemplate.opsForList() -> ListOperations<String, Object>;// 操作 list
* redisTemplate.opsForSet() -> SetOperations<String, Object>;// 操作 set
* redisTemplate.opsForZSet() -> ZSetOperations<String, Object>;// 操作 SortedSet
*/
// 1.操作 String
@Test
public void testString() {
ValueOperations<String, Object> valueOperations = redisTemplate.opsForValue();
// 添加⼀条数据
valueOperations.set("username", "zhangsan");
valueOperations.set("age", "18");
/
/ redis 中以层级关系、⽬录形式存储数据
valueOperations.set("user:01", "lisi");
valueOperations.set("user:02", "wangwu");
// 添加多条数据
Map<String, String> userMap = new HashMap<>();
userMap.put("address", "bj");
userMap.put("sex", "1");
valueOperations.multiSet(userMap);
// 获取⼀条数据
Object username = ("username");
System.out.println(username);
/
/ 获取多条数据
List<String> keys = new ArrayList<>();
keys.add("username");
keys.add("age");
keys.add("address");
keys.add("sex");
List<Object> resultList = valueOperations.multiGet(keys);
for (Object str : resultList) {
System.out.println(str);
}
// 删除
/
/redisTemplate.delete("username");
}
看下结果
操作 hash
@Test
public void testHash() {
HashOperations<String, String, String> hashOperations = redisTemplate.opsForHash();
/*
* 添加⼀条数据
* 参数⼀:redis 的 key
* 参数⼆:hash 的 key
* 参数三:hash 的 value
*/
hashOperations.put("userInfo","name","lisi");
// 添加多条数据
Map<String, String> map = new HashMap();
map.put("age", "20");
map.put("sex", "1");
hashOperations.putAll("userInfo", map);
// 获取⼀条数据
String name = ("userInfo", "name");
System.out.println(name);//lisi
// 获取多条数据
List<String> keys = new ArrayList<>();
keys.add("age");
keys.add("sex");
List<String> resultlist =hashOperations.multiGet("userInfo", keys);
for (String str : resultlist) {
System.out.println(str);
}
// 获取 Hash 类型所有的数据
Map<String, String> userMap = ies("userInfo");
for (Map.Entry<String, String> userInfo : Set()) {
System.out.Key() + "--" + Value());
}
// 删除⽤于删除 hash 类型数据
//hashOperations.delete("userInfo", "name");
}
看下结果
操作 list
@Test
public void testList() {
ListOperations<String, Object> listOperations = redisTemplate.opsForList();
// 左添加(上)
listOperations.leftPush("students", "Wang Wu");
listOperations.leftPush("students", "Li Si");
// 左添加(上) 把 value 值放到 key 对应列表中 pivot 值的左⾯,如果 pivot 值存在的话        listOperations.leftPush("students", "Wang Wu", "Li Si");
// 右添加(下)
listOperations.rightPush("students", "Zhao Liu");
// 获取 start 起始下标 end 结束下标包含关系
List<Object> students = listOperations.range("students", 0,2);
for (Object stu : students) {
System.out.println(stu);
}
// 根据下标获取
Object stu = listOperations.index("students", 1);
System.out.println(stu);
// 获取总条数
Long total = listOperations.size("students");
System.out.println("总条数:" + total);
// 删除单条删除列表中存储的列表中⼏个出现的 Li Si。
//ve("students", 1, "Li Si");
/
/ 删除多条
//redisTemplate.delete("students");
}
看下结果
操作 set
@Test
public void testSet() {
SetOperations<String, Object> setOperations = redisTemplate.opsForSet();
// 添加数据
String[] letters = new String[]{"aaa", "bbb", "ccc", "ddd", "eee"};
//setOperations.add("letters", "aaa", "bbb", "ccc", "ddd", "eee");
setOperations.add("letters", letters);
// 获取数据
Set<Object> let = bers("letters");
for (Object letter: let) {
System.out.println(letter);
}
// 删除
//ve("letters", "aaa", "bbb");
}
看下结果
操作 sorted set
@Test
public void testSortedSet() {
ZSetOperations<String, Object> zSetOperations = redisTemplate.opsForZSet();
ZSetOperations.TypedTuple<Object> objectTypedTuple1 = new DefaultTypedTuple<>("zhangsan", 99D);        ZSetOperations.TypedTuple<Object> objectTypedTuple2 = new DefaultTypedTuple<>("lisi", 96D);
ZSetOperations.TypedTuple<Object> objectTypedTuple3 = new DefaultTypedTuple<>("wangwu", 92D);        ZSetOperations.TypedTuple<Object> objectTypedTuple4 = new DefaultTypedTuple<>("zhaoliu", 100D);        ZSetOperations.TypedTuple<Object> objectTypedTuple5 = new DefaultTypedTuple<>("tianqi", 95D);
Set<ZSetOperations.TypedTuple<Object>> tuples = new HashSet<>();
tuples.add(objectTypedTuple1);
tuples.add(objectTypedTuple2);
tuples.add(objectTypedTuple3);
tuples.add(objectTypedTuple4);
tuples.add(objectTypedTuple5);
// 添加数据
zSetOperations.add("score", tuples);
// 获取数据
Set<Object> scores = zSetOperations.range("score", 0, 4);
for (Object score: scores) {
System.out.println(score);
}
// 获取总条数
Long total = zSetOperations.size("score");
System.out.println("总条数:" + total);
// 删除
//ve("score", "zhangsan", "lisi");
}
看下结果
获取所有 key&删除
// 获取所有 key
@Test
public void testAllKeys() {
// 当前库 key 的名称
Set<String> keys = redisTemplate.keys("*");
for (String key: keys) {
System.out.println(key);
}
}
// 删除
@Test
public void testDelete() {
// 删除通⽤适⽤于所有数据类型
redisTemplate.delete("score");
}
看下结果
public User doQueryUserById(Integer userId) {
// 先从 Redis 查询
User user = (User) redisTemplate.opsForValue().get("user:id_" + userId);
if(null != user){
return user;
}
// Redis 没有再从 mysql 查询
user = userDao.queryUserById(userId);
if(null != user){
redisTemplate.opsForValue().set("user:id_" + userId, user);
return user;
}
return null;
}
public User doQueryUserById2Json(Integer userId) {
// 先从 Redis 查询
Object jsonUser = redisTemplate.opsForValue().get("user:id_" + userId);
User user = null;
if(null != user){
user = JsonUtil.jsonStr2Object((String) jsonUser, User.class);
return user;
}
// Redis 没有再从 mysql 查询
user = userDao.queryUserById(userId);
if(null != user){
redisTemplate.opsForValue().set("user:id_" + userId, JsonUtil.object2JsonStr(user));
return user;
}
return null;
}
问题:如果要直接保存 Bean 对象到 Redis,该如何操作?
1、配置⽂件不能配置序列化操作
a. 配置⽂件不能配置序列化操作,否则会报错。 java.lang.ClassCastException: ity.User cannot be cast to java.lang.String
b. Bean 实体必须实现序列化接⼝
c. 实现⽅式
public User queryUserById(Integer userId) {
// 先从 Redis 查询
User user = (User) redisTemplate.opsForValue().get("user:id_" + userId);

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。