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

相关推荐
java程序员CC17 分钟前
使用springboot+easyexcel实现导出excel并合并指定单元格
spring boot·后端·excel
潘多编程23 分钟前
Spring Boot 3.4 实战指南:从性能优化到云原生增强
spring boot·云原生·性能优化
风象南24 分钟前
SpringBoot中内置的49个常用工具类
java·spring boot·后端
Minyy113 小时前
SpringBoot程序的创建以及特点,配置文件,LogBack记录日志,配置过滤器、拦截器、全局异常
xml·java·spring boot·后端·spring·mybatis·logback
星星点点洲3 小时前
【缓存与数据库结合最终方案】伪从技术
数据库·缓存
武昌库里写JAVA4 小时前
39.剖析无处不在的数据结构
java·vue.js·spring boot·课程设计·宠物管理
Ivan陈哈哈9 小时前
Redis是单线程的,如何提高多核CPU的利用率?
数据库·redis·缓存
李白的粉9 小时前
基于springboot的在线教育系统
java·spring boot·毕业设计·课程设计·在线教育系统·源代码
小马爱打代码10 小时前
SpringBoot原生实现分布式MapReduce计算
spring boot·分布式·mapreduce
iuyou️10 小时前
Spring Boot知识点详解
java·spring boot·后端