SpringBoot整合缓存方式(Caffeine、Redis)

 更新时间:2026年05月06日 09:05:49   作者:加把劲骑士RideOn  
SpringBoot整合缓存注解包括@EnableCaching、@Cachable、@CachePut和@CacheEvict,分别用于配置缓存管理器和标记缓存操作,文章详细介绍了整合Caffeine和Redis缓存的步骤,并展示了配置类与控制层代码,优点是快速应用缓存,缺点是无法精细处理缓存

SpringBoot整合缓存

注解介绍

@EnableCaching

  • 标记在CacheManager统一配置类
  • 需要配合@Configuration使用

@Cachable

  • 标记在需要使用缓存的实现类上,一般用于查询操作。
  • 当该方法输入参数对应的缓存数据不存在与缓存引擎中(类似Redis)时,则会自动生成相关缓存;若存在则直接获取缓存结果。

@CachePut

  • 标记在需要使用缓存的实现类上,一般用于更新操作。
  • 无论如何都会执行方法逻辑,更新到缓存引擎中

@CacheEvict

  • 标记在需要使用缓存的实现类上,一般用于更新操作。
  • 直接清除该缓存

优缺点

  • 优点:可以快速的应用缓存,不必要专业的中间件(例如:CaffeineCache
  • 缺点:无法精细的对缓存做业务处理,只能按照Spring整合缓存提供的逻辑执行(例如:RedisCache)。

依赖

<!--Spring Boot相关-->
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-web</artifactId>
	<version>2.6.8</version>
</dependency>
<!--CaffeineCache-->
<dependency>
	<groupId>com.github.ben-manes.caffeine</groupId>
	<artifactId>caffeine</artifactId>
	<version>2.5.5</version>
</dependency>
<!--Redis-->
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-data-redis</artifactId>
	<version>2.6.8</version>
</dependency>
<dependency>
	<groupId>redis.clients</groupId>
	<artifactId>jedis</artifactId>
	<version>3.7.1</version>
</dependency>

配置文件yml

spring:
  redis:
    host: 127.0.0.1
    port: 6379

整合Caffeine

步骤

1. 在自定义的CacheConfig中配置一个CaffeineCacheManager的@Bean

2. 在实现类中通过@Cachable进行标注(即表示使用哪个引擎CacheManager)

  • 其中,value值对应图一中创建的缓存名称,cacheManager(必填)对应注入的@Bean的名字,
  • 因为如果CachesConfig中存在不同缓存引擎@Bean时(即多个CacheManager都来自一个接口),就会出现@Bean冲突的问题。
  • 解决问题的关键就是使用@Primary指定默认先加载哪个bean,或者就是当下的情况,直接指定cacheManager。

3. 测试缓存结果

代码

CachesConfig配置类

@Configuration
@EnableCaching
public class CachesConfig {
	@Bean(value = "getCaffeineCacheManager")
	public CaffeineCacheManager cacheManager() {
		CaffeineCacheManager cacheManager = new CaffeineCacheManager();
		Cache<Object, Object> cache = Caffeine.newBuilder()
				.expireAfterWrite(5, TimeUnit.SECONDS)
				.maximumSize(10_000)
				.build();
		cacheManager.registerCustomCache("demoCache",cache);
		return cacheManager;
	}
}

CachesController控制层

@RestController
@RequestMapping(value = "cachesController")
public class CachesController {
	@Autowired
	private CachesService cachesService;
	@Autowired
	@Qualifier("getCaffeineCacheManager")
	private CaffeineCacheManager caffeineCacheManager;


	@GetMapping("playCaffeineCaches")
	public <T> T playCaffeineCaches() throws InterruptedException {
		System.out.println(cachesService.getFromDB(1));
		System.out.println(cachesService.getFromDB(1));

		// 校验缓存里的内容~~~~
		Cache demoCache = Objects.requireNonNull(caffeineCacheManager.getCache("demoCache"));
		String s = demoCache.get(1, String.class);
		System.out.println(s);
		// 由于设定Caffeine的过期时间为5s,检验超时后缓存是否失效
		TimeUnit.SECONDS.sleep(10);
		s = demoCache.get(1, String.class);
		System.out.println(s);
		return (T) s;
	}
}

CacheServiceImpl实现类

@Service
@CacheConfig(cacheNames = {"com.devilvan.config.CachesConfig"})
public class CacheServiceImpl implements CachesService {
	@Cacheable(value = {"demoCache"}, cacheManager = "getCaffeineCacheManager", key = "#id")
	@Override
	public Object getFromDB(Integer id) {
		System.out.println("模拟去db查询~~~" + id);
		return "hello cache...";
	}
}

整合Redis缓存

步骤

1. 定义一个RedisTemplate的@Bean

如果不添加其他信息直接注入一个也行

2. 在自定义的CacheConfig中配置一个RedisCacheManager

3. 在实现类中标记@Cachable、@CachePut、@CacheEvict注解,对应缓存的动作

参数

cacheManager

对应配置类中定义的缓存引擎@Bean,CacheManager的实现类

cacheNames

自定义缓存的名字,这里如果定的名字为上图中withCacheConfiguration()方法中的名字,则使用该方法参数中的配置

key

即缓存的对象ID,一般绑定方法参数,当key值在缓存中不存在时,执行逻辑并添加进缓存,存在则直接返回缓存的结果。

代码

CachesConfig配置类

/**
 * 自定义redisTemplate
 */
@Bean
public RedisTemplate<Object, Object> empRedisTemplate(
		RedisConnectionFactory redisConnectionFactory) {
	RedisTemplate<Object, Object> template = new RedisTemplate<>();
	template.setConnectionFactory(redisConnectionFactory);
	// 转换 格式
	template.setKeySerializer(new StringRedisSerializer());
	template.setValueSerializer(new StringRedisSerializer());
	template.setHashKeySerializer(new StringRedisSerializer());
	template.setHashValueSerializer(new StringRedisSerializer());
	return template;
}

/**
 * 基于SpringBoot2 对 RedisCacheManager 的自定义配置
 */
@Bean("empRedisCacheManager")
@Primary
public RedisCacheManager empRedisCacheManager(@Autowired @Qualifier("empRedisTemplate") RedisTemplate<Object,Object> redisTemplate) {
	RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration
			.defaultCacheConfig()
			// 设置key为String
			.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisTemplate.getStringSerializer()))
			// 设置value 为自动转Json的Object
			.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(redisTemplate.getValueSerializer()))
			// 不缓存null
			.disableCachingNullValues()
			// 缓存数据保存30s
			.entryTtl(Duration.ofSeconds(30));
	// 构造一个redis缓存管理器
	RedisCacheManager redisCacheManager = RedisCacheManager
			.RedisCacheManagerBuilder
			// Redis 连接工厂
			.fromConnectionFactory(Objects.requireNonNull(redisTemplate.getConnectionFactory()))
			// 设置默认缓存配置
			.cacheDefaults(redisCacheConfiguration)
			// 设置自定义缓存配置,缓存名为cache_user,它的过期时间为60s
			.withCacheConfiguration("cache_user", redisCacheConfiguration.entryTtl(Duration.ofSeconds(60)))
			// 上面默然缓存时间是1小时,但是可以根据cacheName来设置缓存时间
			.withCacheConfiguration("cache_post", redisCacheConfiguration.entryTtl(Duration.ofSeconds(120)))
			// 配置同步修改或删除 put/evict
			.transactionAware()
			.build();
	return redisCacheManager;
}

CachesController控制层

@GetMapping("playRedisCaches")
public <T> T playRedisCaches(@RequestParam("id") Integer id) {
	System.out.println(cachesService.getDept(id));
	System.out.println(cachesService.getDept(id));
	return (T) null;
}

@PostMapping("updateRedisCaches")
public <T> T updateRedisCaches(@RequestParam("id") Integer id) {
	System.out.println(cachesService.updateDept(id));
	System.out.println(cachesService.getDept(id));
	return (T) null;
}

@DeleteMapping("deleteRedisCaches")
public <T> T deleteRedisCaches(@RequestParam("id") Integer id) {
	cachesService.deleteDept(id);
	System.out.println(cachesService.getDept(id));
	return (T) null;
}

CachesServiceImpl实现类

@Cacheable(cacheManager = "empRedisCacheManager",cacheNames = {"dept"},key = "#id")
@Override
public String getDept(Integer id) {
	System.out.println("查询"+ id  +"号部门。" );
	int i = new Random().nextInt(65535);
	int hashCode = String.valueOf((id + i)).hashCode();
	return "Do you like what you see?" + "-->" +hashCode;
}

@CachePut(cacheManager = "empRedisCacheManager",cacheNames = {"dept"},key = "#id")
@Override
public String updateDept(Integer id) {
	System.out.println("更新"+ id  +"号部门。" );
	int i = new Random().nextInt(65535);
	int hashCode = String.valueOf((id + i)).hashCode();
	return "Do you like what you see?" + "-->" +hashCode;
}

@CacheEvict(cacheManager = "empRedisCacheManager",cacheNames = {"dept"},key = "#id")
@Override
public void deleteDept(Integer id) {
	System.out.println("删除"+ id  +"号部门。" );
}

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • JavaSE详细讲解异常语法

    JavaSE详细讲解异常语法

    异常就是不正常,比如当我们身体出现了异常我们会根据身体情况选择喝开水、吃药、看病、等 异常处理方法。 java异常处理机制是我们java语言使用异常处理机制为程序提供了错误处理的能力,程序出现的错误,程序可以安全的退出,以保证程序正常的运行等
    2022-05-05
  • Java使用Instant时输出的时间比预期少了八个小时

    Java使用Instant时输出的时间比预期少了八个小时

    在Java中,LocalDateTime表示没有时区信息的日期和时间,而Instant表示基于UTC的时间点,本文主要介绍了Java使用Instant时输出的时间比预期少了八个小时的问题解决,感兴趣的可以了解一下
    2024-09-09
  • 详解java.lang.reflect.Modifier.isInterface()方法

    详解java.lang.reflect.Modifier.isInterface()方法

    这篇文章主要介绍了详解java.lang.reflect.Modifier.isInterface()方法的相关资料,这里提供实例帮助大家理解这个方法的使用,需要的朋友可以参考下
    2017-09-09
  • springboot实现执行sql语句打印到控制台

    springboot实现执行sql语句打印到控制台

    这篇文章主要介绍了springboot实现执行sql语句打印到控制台的操作,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-06-06
  • Springboot项目中实现微信小程序登录案例(最新推荐)

    Springboot项目中实现微信小程序登录案例(最新推荐)

    文章介绍了如何通过微信开放平台的授权登录功能实现Spring Boot项目与微信小程序的微信登录,本文通过实例代码给大家介绍的非常详细,感兴趣的朋友一起看看吧
    2025-02-02
  • 有关于整体刷新和局部刷新frameset窗口

    有关于整体刷新和局部刷新frameset窗口

    本篇小编为大家介绍有关于整体刷新和局部刷新frameset窗口的方法,希望对有需要的朋友有所帮助。
    2013-04-04
  • 浅谈标签和JLabel类构造方法

    浅谈标签和JLabel类构造方法

    这篇文章主要介绍了标签和JLabel类构造方法,具有一定参考价值,需要的朋友可以参考下。
    2017-09-09
  • Java中List集合的常用方法详解

    Java中List集合的常用方法详解

    本篇文章给大家带来的内容是关于Java中List集合的常用方法详解,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。下面我们就来学习一下吧
    2021-11-11
  • IntelliJ IDEA 2020.3 重大特性(新功能一览)

    IntelliJ IDEA 2020.3 重大特性(新功能一览)

    这篇文章主要介绍了IntelliJ IDEA 2020.3 重大特性(新功能一览),本文通过图文并茂的形式给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-12-12
  • Java多边形重心计算

    Java多边形重心计算

    今天小编就为大家分享一篇关于Java多边形重心计算,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧
    2019-01-01

最新评论