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

相关推荐
卿雪12 分钟前
Redis 线程模型:Redis为什么这么快?Redis为什么引入多线程?
java·数据库·redis·sql·mysql·缓存·golang
爬山算法17 分钟前
Redis(167)如何使用Redis实现分布式缓存?
redis·分布式·缓存
老华带你飞23 分钟前
汽车销售|汽车报价|基于Java汽车销售系统(源码+数据库+文档)
java·开发语言·数据库·vue.js·spring boot·后端·汽车
TinpeaV24 分钟前
Elasticsearch8(ES)保姆级菜鸟入门教程
大数据·spring boot·elasticsearch·搜索引擎·全文检索·postman
象象翔1 小时前
AI+若依(实战篇)
java·人工智能·spring boot·spring
小王师傅661 小时前
【轻松入门SpringBoot】从 0 到 1 搭建 SpringBoot 工程-中
java·spring boot·spring
qq_348231852 小时前
Spring Boot开发过程中常见问题
java·spring boot·后端
源代码•宸3 小时前
分布式缓存-GO(项目整体架构简介、Ubuntu 22.04 64位安装GoLang、安装Docker、解决Go module 的依赖问题)
经验分享·分布式·后端·ubuntu·缓存·docker·golang
golang学习记3 小时前
Redis Pipeline 实战指南:提升 Go 后端性能的利器
redis·golang·php