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

相关推荐
我命由我1234538 分钟前
Spring Boot 项目集成 Redis 问题:RedisTemplate 多余空格问题
java·开发语言·spring boot·redis·后端·java-ee·intellij-idea
面朝大海,春不暖,花不开38 分钟前
Spring Boot消息系统开发指南
java·spring boot·后端
hshpy40 分钟前
setting up Activiti BPMN Workflow Engine with Spring Boot
数据库·spring boot·后端
jay神1 小时前
基于Springboot的宠物领养系统
java·spring boot·后端·宠物·软件设计与开发
不知几秋2 小时前
Spring Boot
java·前端·spring boot
篱笆院的狗2 小时前
如何使用 Redis 快速实现布隆过滤器?
数据库·redis·缓存
howard20053 小时前
5.4.2 Spring Boot整合Redis
spring boot·整合redis
TracyCoder1233 小时前
接口限频算法:漏桶算法、令牌桶算法、滑动窗口算法
spring boot·spring·限流
小鸡脚来咯3 小时前
redis分片集群架构
数据库·redis·架构
什么都想学的阿超3 小时前
【Redis系列 03】掌握Redis编程艺术:事务、管道与Lua脚本完全指南
redis·junit·lua