Spring boot如何使用redis缓存

引入依赖

这个是参照若依的,如果没有统一的版本规定的话,这里是需要写版本号的

xml 复制代码
<!-- redis 缓存操作 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

定义redis的配置类型

  • 配置类必须加上注解:@Configuration,告诉bean容器这是一个配置类
  • 类中必须有一个方法,返回redis模板的实例对象,此方法必须有一个注解:@Bean,以后使用RedisTemplate 类型的变量注入的时候,就会调用这个方法返回的类实例对象
java 复制代码
/**
 * redis配置
 */
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport
{
    @Bean
    @SuppressWarnings(value = { "unchecked", "rawtypes" })
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory)
    {
        RedisTemplate<Object, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(connectionFactory);

        FastJson2JsonRedisSerializer serializer = new FastJson2JsonRedisSerializer(Object.class);

        // 使用StringRedisSerializer来序列化和反序列化redis的key值
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(serializer);

        // Hash的key也采用StringRedisSerializer的序列化方式
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(serializer);

        template.afterPropertiesSet();
        return template;
    }



}

使用redisTemplate

使用之前需要先注入一下

java 复制代码
@Autowired
private RedisTemplate redisTemplate;

  • 被写入的对象必须支持序列化,所有需要实现接口Serializable
  • 主键
  • 内容
  • 时长
  • 时长单位
java 复制代码
redisTemplate.opsForValue().set(redisKey,new ShiftDto(proDate,shiftId),30, TimeUnit.MINUTES);

  • 主键
bash 复制代码
redisTemplate.delete(redisKey);

  • 主键
java 复制代码
redisTemplate.hasKey(redisKey)

参考文章

https://blog.csdn.net/weixin_51496936/article/details/131469971

相关推荐
openFuyao27 分钟前
在Agent时代,成本与性能权衡成为首要考量:采用以内存缓存为中心的全新拓扑架构,还是坚持以不断提升算力为核心的计算中心架构?
缓存
常常有38 分钟前
Redis:哨兵模式 (Sentinel)
redis·python·sentinel
二哈赛车手38 分钟前
新人笔记---继图片搜索功能后续以及AI网络搜索功能一些经验与踩坑点,吐槽一下自己在做这方面的崩溃瞬间
java·网络·人工智能·spring boot·笔记·spring
逐梦苍穹1 小时前
omlx实战:5分钟让Apple Silicon本地跑通Claude Code——分页SSD KV缓存把TTFT从90秒压到1秒(附安装踩坑+实测)
人工智能·缓存·ollama·claudecode·omlx
javahongxi1 小时前
Spring Cloud Trace 链路实现
java·spring boot·spring cloud
代码丰1 小时前
【面经】缓存一致性全套解决方案:从旁路删除到延迟双删、MQ 补偿、binlog 监听与多级缓存
缓存
屋外雨大,惊蛰出没1 小时前
spring boot+mybatis开发基础复习
java·spring boot·后端
Jul1en_2 小时前
【Redis】事务详解、WATCH 实现思想
java·spring boot·redis·mysql·java-ee
霸道流氓气质2 小时前
异步任务提交 + Redis 状态轮询模式实战指南
数据库·redis·缓存
霸道流氓气质2 小时前
Spring Boot + Jasypt 实战指南:配置文件敏感信息加密完全手册
数据库·spring boot·oracle