springboot 使用ehcache缓存,缓存方法结果

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/woaiqianzhige/article/details/85250376

操作步骤

1.开启缓存
2.设置缓存
3.方法上添加缓存注解

1.开启缓存

启动类上添加 `@EnableCaching` 注解即可开启缓存启用

2.设置缓存

maven如下
 <dependency>
      <groupId>net.sf.ehcache</groupId>
      <artifactId>ehcache</artifactId>
  </dependency>

  <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-cache</artifactId>
  </dependency>

首先创建一个`@Configuration`的配置类,配置两个bean
配置ehcache的cachemanager
//首先配置ehcache的cachemanager,需要导入ehcache的maven,测试用,所以过期时间设置成三秒
//具体详细配置再真实环境中再配置
@Bean
public net.sf.ehcache.CacheManager ehCacheManager() {
	net.sf.ehcache.CacheManager cacheManager = net.sf.ehcache.CacheManager.newInstance();
	Cache cache = new Cache("testCache", 1000, false, false, 3, 2);
	cacheManager.addCache(cache);
	return cacheManager;
}

配置spring的cachemanager 接口的实现类,该接口有多个实现类,这里选择的是使用ehcache类

//把上面的ehcache的cachemanager 传入springcachemanager中,
@Bean
public org.springframework.cache.CacheManager springCacheManager() {
	return new EhCacheCacheManager(ehCacheManager());
}	

至此我们已经开启了缓存,并且配置类ehcache的缓存管理器,并把ehcache的缓存管理器交给了spring的缓存管理器

3.使用缓存

上面我们配置了ehcache的缓存管理器,并创建一个名字叫做testCache 的缓存,接下来使用他
 写一个controller

@Resource
private SessionUserService sessionUserService;

@RequestMapping("test")
@Cacheable(value = "testCache",key = "#orderId") 
public Long test(Long orderId, Long userId){
	Long aLong = sessionUserService.checkOrder(orderId, userId);
	System.out.println("执行了controller");
	return aLong;
}

Cacheable注解表示这个方法开启缓存,并且使用testCache这个缓存,并且缓存的键是参数orderId

启动项目第一次访问接口时,控制台打印出执行了controller,立刻再访问接口,控制台就没有打印了, 等三秒中,再次访问,控制台又打印出执行了controller,说明缓存起效果了,

其他配置,主要关于,缓存时间,缓存策略等,参考ehcache的配置

查看缓存命中率等信息

	net.sf.ehcache.Cache orderDetailCache = cacheManager.getCache("orderDetailCache");
	StatisticsGateway statistics = orderDetailCache.getStatistics();
	long hit = statistics.localHeapHitCount();
	long miss = statistics.localHeapMissCount();
	double rate = (hit + miss > 0) ? hit * 1.0 / (hit + miss) : 0.0;	

猜你喜欢

转载自blog.csdn.net/woaiqianzhige/article/details/85250376