🎓博主介绍:Java、Python、js全栈开发 “多面手”,精通多种编程语言和技术,痴迷于人工智能领域。秉持着对技术的热爱与执着,持续探索创新,愿在此分享交流和学习,与大家共进步。
📖DeepSeek-行业融合之万象视界(附实战案例详解100+)
📖全栈开发环境搭建运行攻略:多语言一站式指南(环境搭建+运行+调试+发布+保姆级详解)
👉感兴趣的可以先收藏起来,希望帮助更多的人
SpringBoot缓存技术全解析:Redis+Caffeine二级缓存架构
一、缓存技术概述
1.1 缓存的概念与作用
缓存是一种数据临时存储的机制,它可以将经常访问的数据存储在高速存储介质中,以减少对低速存储介质(如数据库)的访问,从而提高系统的响应速度和性能。在Web应用中,缓存可以显著减少数据库的负载,降低响应时间,提升用户体验。
1.2 常见的缓存类型
- 本地缓存:如Guava Cache、Caffeine等,存储在应用程序的内存中,访问速度极快,但受限于应用程序的内存大小,不适合存储大量数据。
- 分布式缓存:如Redis、Memcached等,独立于应用程序,多个应用实例可以共享缓存数据,适合大规模分布式系统。
二、Spring Boot缓存框架简介
2.1 Spring Cache
Spring Cache是Spring框架提供的一个缓存抽象层,它为不同的缓存实现提供了统一的编程模型。通过使用@Cacheable
、@CachePut
、@CacheEvict
等注解,可以方便地在方法上添加缓存功能。
2.2 Spring Boot对缓存的支持
Spring Boot对Spring Cache进行了自动配置,只需要添加相应的依赖,就可以快速集成缓存功能。例如,在pom.xml
中添加以下依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
三、Caffeine本地缓存
3.1 Caffeine简介
Caffeine是一个基于Java 8的高性能本地缓存库,它借鉴了Guava Cache的设计思想,并在性能上进行了优化。Caffeine具有高并发、低延迟、支持多种缓存淘汰策略等特点。
3.2 在Spring Boot中集成Caffeine
3.2.1 添加依赖
在pom.xml
中添加Caffeine依赖:
<dependency>
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>caffeine</artifactId>
</dependency>
3.2.2 配置Caffeine缓存管理器
import com.github.ben-manes.caffeine.cache.Caffeine;
import org.springframework.cache.CacheManager;
import org.springframework.cache.caffeine.CaffeineCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.concurrent.TimeUnit;
@Configuration
public class CaffeineCacheConfig {
@Bean
public CacheManager cacheManager() {
CaffeineCacheManager cacheManager = new CaffeineCacheManager();
cacheManager.setCaffeine(Caffeine.newBuilder()
.initialCapacity(100)
.maximumSize(1000)
.expireAfterWrite(10, TimeUnit.MINUTES));
return cacheManager;
}
}
3.2.3 使用Caffeine缓存
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
@Service
public class UserService {
@Cacheable(value = "users", key = "#id")
public User getUserById(Long id) {
// 模拟从数据库中查询用户信息
return new User(id, "John Doe");
}
}
四、Redis分布式缓存
4.1 Redis简介
Redis是一个开源的、高性能的键值对存储数据库,它支持多种数据结构(如字符串、哈希、列表、集合等),并提供了丰富的功能(如缓存、消息队列、分布式锁等)。Redis以内存作为数据存储介质,同时支持数据持久化,适合作为分布式缓存使用。
4.2 在Spring Boot中集成Redis
4.2.1 添加依赖
在pom.xml
中添加Redis依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
4.2.2 配置Redis连接信息
在application.properties
中配置Redis连接信息:
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.password=
4.2.3 配置Redis缓存管理器
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.time.Duration;
@Configuration
@EnableCaching
public class RedisCacheConfig {
@Bean
public RedisCacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
RedisCacheConfiguration cacheConfig = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofMinutes(10))
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));
return RedisCacheManager.builder(redisConnectionFactory)
.cacheDefaults(cacheConfig)
.build();
}
}
4.2.4 使用Redis缓存
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
@Service
public class ProductService {
@Cacheable(value = "products", key = "#id")
public Product getProductById(Long id) {
// 模拟从数据库中查询产品信息
return new Product(id, "iPhone 15");
}
}
五、Redis + Caffeine二级缓存架构
5.1 二级缓存的原理
二级缓存架构结合了本地缓存和分布式缓存的优点,将经常访问的数据存储在本地缓存(Caffeine)中,以提高访问速度;将数据的备份存储在分布式缓存(Redis)中,以保证数据的一致性和可用性。当应用程序需要访问数据时,首先从本地缓存中查找,如果找不到,则从分布式缓存中查找,如果还找不到,则从数据库中查询,并将查询结果同时存入本地缓存和分布式缓存。
5.2 在Spring Boot中实现二级缓存
5.2.1 自定义缓存管理器
import com.github.ben-manes.caffeine.cache.Caffeine;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.caffeine.CaffeineCache;
import org.springframework.cache.support.SimpleCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
@Configuration
@EnableCaching
public class TwoLevelCacheConfig extends CachingConfigurerSupport {
@Bean
public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
SimpleCacheManager cacheManager = new SimpleCacheManager();
List<Cache> caches = new ArrayList<>();
caches.add(new CaffeineCache("localCache", Caffeine.newBuilder()
.initialCapacity(100)
.maximumSize(1000)
.expireAfterWrite(10, TimeUnit.MINUTES)
.build()));
RedisCacheConfiguration cacheConfig = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofMinutes(10))
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));
RedisCacheManager redisCacheManager = RedisCacheManager.builder(redisConnectionFactory)
.cacheDefaults(cacheConfig)
.build();
caches.add(redisCacheManager.getCache("redisCache"));
cacheManager.setCaches(caches);
return cacheManager;
}
}
5.2.2 实现二级缓存逻辑
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
@Service
public class TwoLevelCacheService {
@Cacheable(value = {"localCache", "redisCache"}, key = "#id")
public Data getDataById(Long id) {
// 模拟从数据库中查询数据
return new Data(id, "Data content");
}
}
六、二级缓存的优缺点与适用场景
6.1 优点
- 高性能:本地缓存(Caffeine)的访问速度极快,可以显著减少数据的访问延迟。
- 高可用性:分布式缓存(Redis)可以保证数据的一致性和可用性,即使本地缓存失效,也可以从分布式缓存中获取数据。
- 减轻数据库压力:通过缓存数据,减少了对数据库的访问次数,降低了数据库的负载。
6.2 缺点
- 数据一致性问题:由于本地缓存和分布式缓存的数据可能存在不一致的情况,需要采取相应的措施来保证数据的一致性。
- 缓存穿透、缓存击穿和缓存雪崩问题:需要对这些问题进行处理,以保证系统的稳定性。
6.3 适用场景
- 读多写少的场景:如电商系统的商品信息、新闻系统的文章信息等。
- 对响应时间要求较高的场景:如实时监控系统、在线游戏等。
七、总结
本文详细介绍了Spring Boot中缓存技术的相关知识,包括Caffeine本地缓存、Redis分布式缓存以及Redis + Caffeine二级缓存架构。通过合理使用缓存技术,可以显著提高系统的性能和响应速度,减轻数据库的压力。在实际应用中,需要根据具体的业务场景和需求,选择合适的缓存方案,并处理好缓存带来的各种问题。