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

相关推荐
小胖java5 分钟前
养老院管理系统
java·spring boot
ZHOUPUYU5 分钟前
从缓存到消息队列的全面应用,PHP与Redis深度实战
redis·缓存·php
永远睡不够的入34 分钟前
C++继承详解
java·c++·redis
moxiaoran575339 分钟前
使用springboot+flowable实现一个简单的订单审批工作流
java·spring boot·后端
计算机徐师兄2 小时前
Java基于SpringBoot的运动健康小程序【附源码、文档说明】
spring boot·小程序·运动健康·java运动健康小程序·运动健康小程序·java运动健康微信小程序·运动健康微信小程序
计算机学姐2 小时前
基于SpringBoot的网吧管理系统
java·spring boot·后端·spring·tomcat·intellij-idea·mybatis
Boop_wu2 小时前
[Java EE 进阶] SpringBoot 配置文件全解析:properties 与 yml 的使用(1)
java·spring boot·spring·java-ee
ywf12154 小时前
前端的dist包放到后端springboot项目下一起打包
前端·spring boot·后端
大阿明10 小时前
Spring Boot(快速上手)
java·spring boot·后端
哆啦A梦158810 小时前
Springboot整合MyBatis实现数据库操作
数据库·spring boot·mybatis