spring boot 缓存_「快学SpringBoot」Spring Cache+Redis实现高可用缓存解决方案

往期文章

「快学SpringBoot」快速上手好用方便的Spring Cache缓存框架

Docker+SpringBoot快速构建和部署应用

「快学Docker」Docker简介、安装和Hello World实现

「快学Docker」Docker镜像相关的常用操作

前言

之前已经写过一篇文章介绍SpringBoot整合Spring Cache,SpringBoot默认使用的是ConcurrentMapCacheManager,在实际项目中,我们需要一个高可用的、分布式的缓存解决方案,使用默认的这种缓存方式,只是在当前进程里缓存了而已。Spring Cache整合Redis来实现缓存,其实也不是一件复杂的事情,下面就开始吧。

关于Spring Cache的运用,请参考[快学SpringBoot]快速上手好用方便的Spring Cache缓存框架

新建一个SpringBoot项目

依赖

org.springframework.boot spring-boot-starter-web ​ org.springframework.boot spring-boot-devtools runtimetrueorg.springframework.boot spring-boot-configuration-processor trueorg.projectlombok lombok trueorg.springframework.boot spring-boot-starter-test testorg.springframework.boot spring-boot-starter-cache org.springframework.boot spring-boot-starter-data-redis 

主要是最下面两个依赖:spring-boot-starter-cache 和 spring-boot-starter-data-redis。

配置Redis

在application.properties中添加redis的配置

spring.redis.host=127.0.0.1# spring.redis.password=spring.redis.port=6379

这是最基础的三个配置(其实默认值就是这样,就算不写也可以)。当然,还有空闲连接数,超时时间,最大连接数等参数,我这里都没有设置,在生产项目中,根据实际情况设置。

RedisCacheConfig

新建RedisCacheConfig.class

@Configuration@EnableCachingpublic class RedisCacheConfig {​ /** * 缓存管理器 */ @Bean public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) { //初始化一个RedisCacheWriter RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory); //设置CacheManager的值序列化方式为json序列化 RedisSerializer jsonSerializer = new GenericJackson2JsonRedisSerializer(); RedisSerializationContext.SerializationPair pair = RedisSerializationContext.SerializationPair .fromSerializer(jsonSerializer); RedisCacheConfiguration defaultCacheConfig=RedisCacheConfiguration.defaultCacheConfig() .serializeValuesWith(pair); return new RedisCacheManager(redisCacheWriter, defaultCacheConfig); }​}

如果要设置缓存管理器所管理的缓存名字,RedisCacheManager构造方法提供一个可变参数的构造器:

c762fcb48fc3bd6d7e7291b2efaa4985.png

测试

新建一个MockService.java,代码如下:

@Servicepublic class MockService {​ /** * value 缓存的名字,与cacheName是一个东西 * key 需要缓存的键,如果为空,则会根据参数自动拼接 * 写法:SpEL 表达式 */ @Cacheable(value = "listUsers
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值