基于Redis封装一个分布式多级缓存框架
1.技术栈:
1、Redis缓存的使用
2、ehcache缓存的使用
3、使用aop切面编程
4、Redis发布与订阅
5、自定义注解 + spel表达式
2.封装步骤
2.1 创建Maven工程
2.1.1导入相关依赖
<parent>
<artifactId>spring-boot-starter-parent</artifactId>
<groupId>org.springframework.boot</groupId>
<version>2.3.0.RELEASE</version>
</parent>
<groupId>com.feilong.cache</groupId>
<artifactId>cache-spring-boot-starter</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!--ehcache缓存-->
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
</dependencies>
2.2编写多级缓存的核心配置类
@Configuration
@ComponentScan("com.feilong.cache")
public class MyCacheConfiguration {
/**
* 配置Ehcache(本地缓存====》》》一级缓存)
*
* @return
*/
@Bean
public CacheManager getCacheManager() {
//创建一个缓存配置对象
CacheConfiguration cacheConfiguration = new CacheConfiguration();
//设置缓存名
cacheConfiguration.setName("JVM-CACHE");
//设置最大缓存数量
cacheConfiguration.setMaxElementsInMemory(100000);
//设置缓存的存活时间
cacheConfiguration.setTimeToLiveSeconds(300);
//设置缓存的空闲时间
cacheConfiguration.setTimeToIdleSeconds(300);
//配置Ehcache的配置类
net.sf.ehcache.config.Configuration configuration = new net.sf.ehcache.config.Configuration();
configuration.addCache(cacheConfiguration);
CacheManager cacheManager = new CacheManager(configuration);
return cacheManager;
}
@Bean
public RedisMessageListenerContainer getRedisMessage(RedisConnectionFactory connectionFactory, CacheDelListener cacheDelListener){
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(connectionFactory);
container.addMessageListener(cacheDelListener, new ChannelTopic("cacheChannel"));
return container;
}
}
2.3 编写自定义注解
/**
* @author FeiLong
* @version 1.8
* @date 2020/11/26 16:24
*
* 缓存使用的注解
*/
@SuppressWarnings("ALL")
@Target(ElementType.METHOD)
@Documented
@Retention(RetentionPolicy.RUNTIME)
public @<