Spring boot如何使用redis缓存

10 篇文章 0 订阅

引入依赖

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

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

定义redis的配置类型

  • 配置类必须加上注解:@Configuration,告诉bean容器这是一个配置类
  • 类中必须有一个方法,返回redis模板的实例对象,此方法必须有一个注解:@Bean,以后使用RedisTemplate 类型的变量注入的时候,就会调用这个方法返回的类实例对象
/**
 * 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

使用之前需要先注入一下

@Autowired
private RedisTemplate redisTemplate;

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

  • 主键
redisTemplate.delete(redisKey);

  • 主键
redisTemplate.hasKey(redisKey)

参考文章

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

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值