springboot整个缓存_springboot 整合ehcache缓存

1、CacheManager

Spring Boot默认集成CacheManager,如下包所示:

可以看出springboot自动配置了 JcacheCacheConfiguration、 EhCacheCacheConfiguration、HazelcastCacheConfiguration、GuavaCacheConfiguration、RedisCacheConfiguration、SimpleCacheConfiguration 等。

默认的CacheManager为ConcurrenMapCacheManager,Spring从Spring3.1开始基于java.util.concurrent.ConcurrentHashMap实现的缓存管理器。Spring Boot 默认使用 ConcurrentMapCacheManager作为缓存技术。新建一个springboot项目,直接使用cache相关注解来测试,效果如下:

2、整合encache

pom依赖引入

org.springframework.boot

spring-boot-starter-cache

net.sf.ehcache

ehcache

application文件配置

spring:

cache:

#ehcache配置文件路径

ehcache:

config: classpath:/ehcache/ehcache.xml

#指定缓存类型,可加可不加

#type: ehcache

encache.xml文件

/>

/>

启动类加上启用缓存注解

@EnableCachingpublic classSpringbootCacheApplication {public static voidmain(String[] args) {

SpringApplication.run(SpringbootCacheApplication.class, args);

}

}

代码中使用cache注解

@Servicepublic class UserServiceImpl implementsUserService {

@AutowiredprivateUserMapper userMapper;//使用ehcache配置的缓存名users_test

private final String USER_CACHE_NAME = "users_test";

@Overridepublic ListlistUser() {returnuserMapper.selectUserList();

}

@Override//@Cacheable(value = USER_CACHE_NAME, key = "#id")

@Cacheable(value = USER_CACHE_NAME, key = "'user' + #id")publicUser selectUserById(Integer id) {returnuserMapper.selectUserById(id);

}

@Override//@CacheEvict(value = USER_CACHE_NAME, key = "#id")

@CacheEvict(value = USER_CACHE_NAME, key = "'user_' + #id")public voiddelete(Integer id) {

userMapper.delete(id);

}

@Override//@CacheEvict(value = USER_CACHE_NAME, key = "#user.userId")

@CacheEvict(value = USER_CACHE_NAME, key = "'user' + #user.userId")//@CachePut(value = USER_CACHE_NAME, key = "'user' + #user.userId")//测试发现只将结果清除,key未清除,导致查询继续使用缓存但结果为空????

public voidupdate(User user) {

userMapper.update(user);

}

}

项目启动后查看CacheManager,如下图所示则表示整合ehcache成功

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值