SpringBoot整合ehcache实现

SpringBoot整合ehcache实现

本文基于SpringBoot2.7.2 版本进行讲解,整合ehcache,关于ehcache的介绍请自行查询相关文档。
Spring cache 实现也是参考JSR107规范来实现

Spring Cache相关关键类

Spring CacheJSR107备注
CacheManagerCacheManager提供Cache相关管理
CacheResolverCachingProvider提供创建CacheManager,JSR107 基于SPI实现
CacheCache提供缓存数据操作
Configuration提供Cache configuration
KeyGeneratorKeyGenerator生成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

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值