高效缓存策略:Spring Boot 应用中的混合缓存
现代应用开发中,性能和可扩展性是决定系统成败的关键因素。缓存通过减少数据库负载、降低延迟和确保无缝用户体验,在提升这些方面发挥着关键作用。然而,没有一种单一的缓存解决方案能够完美适应所有场景。
本地缓存(例如 Caffeine)由于在内存中运行并靠近应用程序,因此能够提供极快的速度。它们非常适合减少频繁访问数据的响应时间。另一方面,分布式缓存(例如使用 Redis 的 Redisson)在应用程序的多个实例之间提供可扩展性和一致性。分布式缓存确保分布式系统中的所有节点访问相同最新的数据,这在多节点环境中至关重要。
然而,仅仅依赖本地或分布式缓存都会带来挑战:
- 本地缓存在分布式环境中可能变得不一致,因为数据更新不会在节点之间同步。
- 分布式缓存会引入轻微的网络延迟,这可能不适用于超低延迟场景。
这就是 混合缓存成为有效解决方案的地方。通过结合使用 Caffeine 和 Redisson 的本地和分布式缓存的优势,您可以获得本地缓存速度带来的高性能,同时利用分布式缓存保持一致性和可扩展性。
本文探讨如何在 Spring Boot 应用程序中实现混合缓存,以确保最佳性能和数据一致性。
实现步骤
步骤 1:添加依赖
首先,将必要的依赖项添加到您的 pom.xml
文件中:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency> <dependency> <groupId>com.github.ben-manes.caffeine</groupId> <artifactId>caffeine</artifactId> <version>3.2.0</version> </dependency> <dependency> <groupId>org.redisson</groupId> <artifactId>redisson</artifactId> <version>3.43.0</version> </dependency>
步骤 2:配置缓存
以下是缓存配置:
@Configuration @EnableCaching public class CacheConfig implements CachingConfigurer { @Value("${cache.server.address}") private String cacheAddress; @Value("${cache.server.password}") private String cachePassword; @Value("${cache.server.expirationTime:60}") private Long cacheExpirationTime; @Bean(destroyMethod = "shutdown") RedissonClient redisson() { Config config = new Config(); config.useSingleServer().setAddress(cacheAddress).setPassword(cachePassword.trim()); config.setLazyInitialization(true); return Redisson.create(config); } @Bean @Override public CacheManager cacheManager() { CaffeineCacheManager cacheManager = new CaffeineCacheManager(); cacheManager.setCaffeine(Caffeine.newBuilder().expireAfterWrite(cacheExpirationTime, TimeUnit.MINUTES)); return cacheManager; } @Bean public CacheEntryRemovedListener cacheEntryRemovedListener() { return new CacheEntryRemovedListener(cacheManager()); } @Bean @Override public CacheResolver cacheResolver() { return new LocalCacheResolver(cacheManager(), redisson(), cacheEntryRemovedListener()); } }
关键组件详解
1. 缓存管理器 (CacheManager)
CacheManager
负责管理缓存的生命周期,并提供对适当缓存实现(例如本地或分布式)的访问。在本例中,我们使用 CaffeineCacheManager
来启用内存缓存,并通过 Caffeine
配置过期策略。
2. 缓存解析器 (CacheResolver)
CacheResolver
动态地确定要对特定操作使用哪个缓存。在这里,LocalCacheResolver
连接本地(Caffeine)和分布式(Redisson)缓存,确保有效应用混合策略。
@Component public class LocalCacheResolver implements CacheResolver { // ... (代码与原文相同) ... }
public class LocalCache implements Cache { // ... (代码与原文相同) ... }
3. 缓存条目移除监听器 (CacheEntryRemovedListener)
CacheEntryRemovedListener
监听从分布式缓存(Redis)中移除的条目,并确保它们也从各个节点的本地缓存中移除,从而保持一致性。
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency> <dependency> <groupId>com.github.ben-manes.caffeine</groupId> <artifactId>caffeine</artifactId> <version>3.2.0</version> </dependency> <dependency> <groupId>org.redisson</groupId> <artifactId>redisson</artifactId> <version>3.43.0</version> </dependency>
混合缓存工作流程
缓存条目添加
当执行用 @Cacheable
注解的方法时,将调用 put
方法。这会将数据存储在本地缓存 (Caffeine) 和分布式缓存 (Redis) 中:
@Configuration @EnableCaching public class CacheConfig implements CachingConfigurer { @Value("${cache.server.address}") private String cacheAddress; @Value("${cache.server.password}") private String cachePassword; @Value("${cache.server.expirationTime:60}") private Long cacheExpirationTime; @Bean(destroyMethod = "shutdown") RedissonClient redisson() { Config config = new Config(); config.useSingleServer().setAddress(cacheAddress).setPassword(cachePassword.trim()); config.setLazyInitialization(true); return Redisson.create(config); } @Bean @Override public CacheManager cacheManager() { CaffeineCacheManager cacheManager = new CaffeineCacheManager(); cacheManager.setCaffeine(Caffeine.newBuilder().expireAfterWrite(cacheExpirationTime, TimeUnit.MINUTES)); return cacheManager; } @Bean public CacheEntryRemovedListener cacheEntryRemovedListener() { return new CacheEntryRemovedListener(cacheManager()); } @Bean @Override public CacheResolver cacheResolver() { return new LocalCacheResolver(cacheManager(), redisson(), cacheEntryRemovedListener()); } }
缓存条目获取
要检索数据,系统首先检查本地缓存中是否存在该键。如果找不到该键,则查询分布式缓存。如果分布式缓存中存在该值,则将其添加到本地缓存中,以便更快地进行后续访问:
@Component public class LocalCacheResolver implements CacheResolver { // ... (代码与原文相同) ... }
缓存条目驱逐
当发生缓存驱逐时(例如,通过 @CacheEvict
注解),该键将从分布式缓存中移除。其他节点的本地缓存将通过 CacheEntryRemovedListener
收到通知,以移除相同的键:
public class LocalCache implements Cache { // ... (代码与原文相同) ... }
总结
混合缓存结合了本地内存缓存的速度和分布式缓存的可扩展性和一致性。这种方法解决了仅使用本地或分布式缓存的局限性。通过在 Spring Boot 应用程序中集成 Caffeine 和 Redisson,您可以实现显著的性能改进,同时确保应用程序节点之间的数据一致性。
使用 CacheEntryRemovedListener
和 CacheResolver
可以确保缓存条目在所有缓存层之间保持同步,为现代可扩展应用程序提供高效且可靠的缓存策略。这种混合方法在分布式系统中尤其宝贵,因为在这些系统中,性能和一致性都至关重要。
以上是春季启动中的混合缓存策略:Redisson和咖啡因整合的指南的详细内容。更多信息请关注PHP中文网其他相关文章!

Javaremainsagoodlanguageduetoitscontinuousevolutionandrobustecosystem.1)Lambdaexpressionsenhancecodereadabilityandenablefunctionalprogramming.2)Streamsallowforefficientdataprocessing,particularlywithlargedatasets.3)ThemodularsystemintroducedinJava9im

Javaisgreatduetoitsplatformindependence,robustOOPsupport,extensivelibraries,andstrongcommunity.1)PlatformindependenceviaJVMallowscodetorunonvariousplatforms.2)OOPfeatureslikeencapsulation,inheritance,andpolymorphismenablemodularandscalablecode.3)Rich

Java的五大特色是多态性、Lambda表达式、StreamsAPI、泛型和异常处理。1.多态性让不同类的对象可以作为共同基类的对象使用。2.Lambda表达式使代码更简洁,特别适合处理集合和流。3.StreamsAPI高效处理大数据集,支持声明式操作。4.泛型提供类型安全和重用性,编译时捕获类型错误。5.异常处理帮助优雅处理错误,编写可靠软件。

java'stopfeatureSnificallyEnhanceItsperFormanCeanDscalability.1)对象 - 方向 - incipleslike-polymormormormormormormormormormormormormorableablefleandibleandscalablecode.2)garbageCollectionAutoctionAutoctionAutoctionAutoctionAutoctionautomorymanatesmemorymanateMmanateMmanateMmanagementButCancausElatenceiss.3)

JVM的核心组件包括ClassLoader、RuntimeDataArea和ExecutionEngine。1)ClassLoader负责加载、链接和初始化类和接口。2)RuntimeDataArea包含MethodArea、Heap、Stack、PCRegister和NativeMethodStacks。3)ExecutionEngine由Interpreter、JITCompiler和GarbageCollector组成,负责bytecode的执行和优化。

Java'ssafetyandsecurityarebolsteredby:1)strongtyping,whichpreventstype-relatederrors;2)automaticmemorymanagementviagarbagecollection,reducingmemory-relatedvulnerabilities;3)sandboxing,isolatingcodefromthesystem;and4)robustexceptionhandling,ensuringgr

javaoffersseveralkeyfeaturesthatenhancecodingskills:1)对象 - 方向 - 方向上的贝利奥洛夫夫人 - 启动worldentities

thejvmisacrucialcomponentthatrunsjavacodebytranslatingitolachine特定建筑,影响性能,安全性和便携性。1)theclassloaderloader,links andinitializesClasses.2)executionEccutionEngineExecutionEngineExecutionEngineExecuteByteCuteByteCuteByteCuteBytecuteBytecuteByteCuteByteCuteByteCuteBytecuteByteCodeNinstRonctientions.3)Memo.3)Memo


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

WebStorm Mac版
好用的JavaScript开发工具

SecLists
SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

mPDF
mPDF是一个PHP库,可以从UTF-8编码的HTML生成PDF文件。原作者Ian Back编写mPDF以从他的网站上“即时”输出PDF文件,并处理不同的语言。与原始脚本如HTML2FPDF相比,它的速度较慢,并且在使用Unicode字体时生成的文件较大,但支持CSS样式等,并进行了大量增强。支持几乎所有语言,包括RTL(阿拉伯语和希伯来语)和CJK(中日韩)。支持嵌套的块级元素(如P、DIV),

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

Atom编辑器mac版下载
最流行的的开源编辑器