设计通用缓存接口,工具类实现下面业务需求:
1.缓存分两种,一个方式缓存在内存中,一种方式缓存到redis中
2.支持可配置,项目中只能使用其中一种方式
3.如果使用redis需要使用Lettuce客户端
4.如果是使用缓存在内存需要使用caffeine
5.无论使用哪种缓存机制都要保证支持高并发
将需求深化
接下来,我们需要定义一些基本的接口和类来描述这个通用缓存工具类,例如:
缓存接口 Cache:
put(Object key, Object value):将值 value 存储到缓存中,使用 key 作为键
get(Object key):从缓存中获取键 key 所对应的值
内存缓存类 MemoryCache:
实现 Cache 接口
使用 Caffeine 来实现缓存
Redis 缓存类 RedisCache:
实现 Cache 接口
使用 Lettuce 客户端连接 Redis 数据库来实现缓存
缓存工厂类 CacheFactory:
根据配置返回对应的缓存实例
在这里,我们可以使用 Spring Boot 的自动配置来实现缓存工厂类的自动装配。我们可以定义一个配置类,通过条件注解来控制使用哪种缓存方式。比如:
@Configuration
public class CacheConfiguration {
@Bean
@ConditionalOnProperty(name = "cache.type", havingValue = "memory")
public Cache memoryCache() {
return new MemoryCache();
}
@Bean
@ConditionalOnProperty(name = "cache.type", havingValue = "redis")
public Cache redisCache() {
return new RedisCache();
}
@Bean
public CacheFactory cacheFactory() {
return new CacheFactory();
}
}
这里我们使用了 @ConditionalOnProperty 注解来根据配置文件中的 cache.type 属性值来选择使用哪种缓存方式。如果 cache.type 的值为 memory,则使用 MemoryCache 类,如果为 redis,则使用 RedisCache 类。
在 CacheFactory 类中,我们可以定义一个 createCache() 方法来根据配置来创建相应的缓存实例。比如:
public class CacheFactory {
private static final String CACHE_TYPE_PROPERTY = "cache.type";
private static final String DEFAULT_CACHE_TYPE = "memory";
private Cache cache;
public CacheFactory() {
String cacheType = System.getProperty(CACHE_TYPE_PROPERTY, DEFAULT_CACHE_TYPE);
this.cache = createCache(cacheType);
}
public Cache getCache() {
return cache;
}
private static Cache createCache(String cacheType) {
switch (cacheType) {
case "redis":
return new RedisCache();
default:
return new MemoryCache();
}
}
}