docker安装Redis参考我另一篇博客Docker安装Redis及持久化
一、Get-Started
依赖
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!--Apache对象池技术,包括RedisConnecttionFactory等,引入这个依赖就不需要自己配置了-->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
yml配置
spring:
redis:
host: 192.168.150.101
password: 123321
lettuce:
pool:
max-active: 8
max-idle: 8
min-idle: 1
max-wait: 300
测试
package com.gzdemo.redisdemo;
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.RedisTemplate;
@SpringBootTest
public class RedisTemplateTest {
@Autowired
private RedisTemplate redisTemplate;
@Test
void testAdd() {
// String
redisTemplate.opsForValue().set("name","zhangsan");
// set
redisTemplate.opsForSet().add("myset","1");
// zset
redisTemplate.opsForZSet().add("myzset","stu1",10);
//hash
redisTemplate.opsForHash().put("myhash","stu1","1");
//list
redisTemplate.opsForList().leftPush("mylist","1");
}
}
运行单元测试,发现redis保存的这5个键值对出现乱码,原因是RedisTemplate默认使用的是Jdk序列化器。
二、StringRedisTemplate
RedisTemplate常用方法:https://blog.csdn.net/zzvar/article/details/118388897
先运行单元测试把新增的5个数据删掉
@Test
void testRemove() {
// String
redisTemplate.delete("name");
// set
redisTemplate.opsForSet().remove("myset","1");
// zset
redisTemplate.opsForZSet().remove("myzset","stu1");
//hash
redisTemplate.opsForHash().delete("myhash","stu1");
//list
redisTemplate.opsForList().rightPop("mylist");
}
将RedisTemplate换成StringRedisTemplate(使用了String序列化器)或者RedisTemplate<String,String>,不能是RedisTemplate<String,Object>
重新测试TestAdd
三、实际开发
实际开发中,在使用到缓存的地方,定义一个业务工具类。这里举个例子,基于LearningRecord实体类,比如
import cn.hutool.json.JSONUtil;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import java.time.Duration;
import java.time.LocalDateTime;
...
@Component
@Slf4j
@RequiredArgsConstructor
public class LearningRecordCacheHandler {
private final StringRedisTemplate redisTemplate;
private final ILearningLessonService lessonService;
private final LearningRecordMapper recordMapper;
// 缓存前缀
private static final String LEARNING_RECORD_CACHE_PREFIX="learning:record:";
//1) 写入缓存
public void writeRecordCache(LearningRecord record){
log.info("缓存放入了消息:");
// 1.转成只有三个属性的对象
RecordCacheData cacheData = new RecordCacheData(record);
// 2. 转成json 字符串
String jsonData = JSONUtil.toJsonStr(cacheData);
// 3 拼接key learning:record:6688
String key =LEARNING_RECORD_CACHE_PREFIX+record.getLessonId();
// 4 存储缓存(覆盖)
redisTemplate.opsForHash().put(key,record.getSectionId().toString(),jsonData);
// 5 设置超时时间
redisTemplate.expire(key, Duration.ofSeconds(60));
}
//2) 读取缓存
public LearningRecord readRecordCache(Long lessonId,Long sectionId){
//1 拼接key learning:record:6688
String key =LEARNING_RECORD_CACHE_PREFIX+lessonId;
// 真正的是String
Object o = redisTemplate.opsForHash().get(key, sectionId.toString());
if(o==null){
return null;
}
// {id:1,moment:30,finshsend:false}
// 转成对象
LearningRecord record = JSONUtil.toBean(o.toString(), LearningRecord.class);
record.setLessonId(lessonId);
record.setSectionId(sectionId);
return record;
}
//3) 删除缓存
public void removeRecordCache(Long lessonId,Long sectionId){
//1 拼接key learning:record:6688
String key =LEARNING_RECORD_CACHE_PREFIX+lessonId;
redisTemplate.opsForHash().delete(key,sectionId.toString());
}
// 存储缓存的对象
@Data
@NoArgsConstructor
public class RecordCacheData{
private Long id;
private Boolean finished;
private Integer moment;
public RecordCacheData(LearningRecord record) {
this.id = record.getId();
this.finished = record.getFinished();
this.moment = record.getMoment();
}
}
}