构建以caffeine为L1,Redis为L2的多级缓存
要构建一个以Caffeine为L1缓存,Redis为L2缓存的多级缓存系统,你可以使用Spring Cache抽象和相应的实现。以下是一个简单的例子:
- 在
pom.xml
中添加依赖:
<dependencies>
<!-- Spring Boot Cache Abstraction -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<!-- Caffeine Cache -->
<dependency>
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>caffeine</artifactId>
</dependency>
<!-- Redis Cache -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
</dependencies>
- 配置CacheManager:
import com.github.benmanes.caffeine.cache.Caffeine;
import org.springframework.cache.CacheManager;
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.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import java.time.Duration;
@Configuration
@EnableCaching
public class CacheConfig {
@Bean
public CacheManager cacheManager(RedisTemplate redisTemplate) {
RedisCacheConfiguration cacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofMinutes(10)) // 缓存有效期10分钟
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));
return RedisCacheManager.builder()
.cacheDefaults(cacheConfiguration)
.transactionAware()
.build();
}
@Bean
public com.github.benmanes.caffeine.cache.Cache<Object, Object> caffeineCache() {
return Caffeine.newBuilder()
.expireAfterWrite(10, java.util.concurrent.TimeUnit.MINUTES) // L1缓存有效期10分钟
.build();
}
}
- 使用缓存:
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.
评论已关闭