SpringBoot整合ehcache实现
本文基于SpringBoot2.7.2 版本进行讲解,整合ehcache,关于ehcache的介绍请自行查询相关文档。
Spring cache 实现也是参考JSR107规范来实现
Spring Cache相关关键类
Spring Cache | JSR107 | 备注 |
---|---|---|
CacheManager | CacheManager | 提供Cache相关管理 |
CacheResolver | CachingProvider | 提供创建CacheManager,JSR107 基于SPI实现 |
Cache | Cache | 提供缓存数据操作 |
Configuration | 提供Cache configuration | |
KeyGenerator | KeyGenerator | 生成key |
Spring Cache 注解
注解 | 注解描述 |
---|---|
Cacheable | 作用于方法,会更加参数进行,返回值缓存 |
CacheConfig | 作用类上面,用于统一配置key、cacheNames等 |
CacheEvict | 清空缓存 |
CachePut | 作用于方法,保证方法被调后,返回结果被缓存起来,一般用于更新操作 |
整合步骤
- 添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>javax.cache</groupId>
<artifactId>cache-api</artifactId>
</dependency>
<dependency>
<groupId>org.ehcache</groupId>
<artifactId>ehcache</artifactId>
</dependency>
- 配置ehcache
配置有两种方式- 通过xml来配置
- 通过springboot提供的cache属性来配置
spring: cache: cache-names: indexService jcache: config: classpath*:encache-setting.xml
- 添加@EnableCaching 开启注解
- 代码中添加相关缓存注解
@CacheConfig(cacheNames = "indexService",keyGenerator ="customerKeyGenerator")
@Service
public class IndexService {
@Cacheable
public String getIndexNum(String str) {
return str;
}
}
@Component(value = "customerKeyGenerator")
public class CustomerKeyGenerator implements KeyGenerator {
@Override
public Object generate(Object target, Method method, Object... params) {
return target.getClass().getSimpleName() + "_"
+ method.getName() + "_"
+ StringUtils.arrayToDelimitedString(params, "_");
}
}
具体代码可以参考github demo