博主介绍:Java、Python、js全栈开发 “多面手”,精通多种编程语言和技术,痴迷于人工智能领域。秉持着对技术的热爱与执着,持续探索创新,愿在此分享交流和学习,与大家共进步。
DeepSeek-行业融合之万象视界(附实战案例详解100+)
全栈开发环境搭建运行攻略:多语言一站式指南(环境搭建+运行+调试+发布+保姆级详解)
感兴趣的可以先收藏起来,希望帮助更多的人
缓存是一种数据临时存储的机制,它可以将经常访问的数据存储在高速存储介质中,以减少对低速存储介质(如数据库)的访问,从而提高系统的响应速度和性能。在Web应用中,缓存可以显著减少数据库的负载,降低响应时间,提升用户体验。
Spring Cache是Spring框架提供的一个缓存抽象层,它为不同的缓存实现提供了统一的编程模型。通过使用@Cacheable
、@CachePut
、@CacheEvict
等注解,可以方便地在方法上添加缓存功能。
Spring Boot对Spring Cache进行了自动配置,只需要添加相应的依赖,就可以快速集成缓存功能。例如,在pom.xml
中添加以下依赖:
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-cacheartifactId>
dependency>
Caffeine是一个基于Java 8的高性能本地缓存库,它借鉴了Guava Cache的设计思想,并在性能上进行了优化。Caffeine具有高并发、低延迟、支持多种缓存淘汰策略等特点。
在pom.xml
中添加Caffeine依赖:
<dependency>
<groupId>com.github.ben-manes.caffeinegroupId>
<artifactId>caffeineartifactId>
dependency>
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;
}
}
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是一个开源的、高性能的键值对存储数据库,它支持多种数据结构(如字符串、哈希、列表、集合等),并提供了丰富的功能(如缓存、消息队列、分布式锁等)。Redis以内存作为数据存储介质,同时支持数据持久化,适合作为分布式缓存使用。
在pom.xml
中添加Redis依赖:
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-data-redisartifactId>
dependency>
在application.properties
中配置Redis连接信息:
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.password=
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();
}
}
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");
}
}
二级缓存架构结合了本地缓存和分布式缓存的优点,将经常访问的数据存储在本地缓存(Caffeine)中,以提高访问速度;将数据的备份存储在分布式缓存(Redis)中,以保证数据的一致性和可用性。当应用程序需要访问数据时,首先从本地缓存中查找,如果找不到,则从分布式缓存中查找,如果还找不到,则从数据库中查询,并将查询结果同时存入本地缓存和分布式缓存。
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;
}
}
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");
}
}
本文详细介绍了Spring Boot中缓存技术的相关知识,包括Caffeine本地缓存、Redis分布式缓存以及Redis + Caffeine二级缓存架构。通过合理使用缓存技术,可以显著提高系统的性能和响应速度,减轻数据库的压力。在实际应用中,需要根据具体的业务场景和需求,选择合适的缓存方案,并处理好缓存带来的各种问题。