1.使用场景:
高频次访问
数据时效性要求不高
数据获取比较难(经过一定的计算)
2.使用的意义:
提高反馈速度
节省计算资源(当然,这个一般比较次要)
上例子
1.类路径下添加ehcache.xml配置文件
2.添加缓存管理器(采用注解的方式)
3.在被应用的方法上使用@Cacheable即可,当然Ehcache的注解比较多这里不做过多讲解
代码如下:
package com.didi.controller;
import net.sf.ehcache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.cache.ehcache.EhCacheManagerFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
@Configuration
@EnableCaching
public class CachingConfig {
@Bean
public EhCacheCacheManager cacheManager(CacheManager cm){
return new EhCacheCacheManager(cm);
}
@Bean
public EhCacheManagerFactoryBean ehcache(){
EhCacheManagerFactoryBean ehCacheManagerFactoryBean = new EhCacheManagerFactoryBean();
ehCacheManagerFactoryBean.setConfigLocation(new ClassPathResource("ehcache.xml"));
return ehCacheManagerFactoryBean;
}
}
package com.didi.controller;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
@Service
@Cacheable(“tasks”)
public class HelloService {
public String hello(int num){
System.out.println("没走缓存");
return "没走缓存";
}
}
编辑器没弄明白,配置文件没copy过来,可以随便在网上找个
ehcache xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
xsi:noNamespaceSchemaLocation=”ehcache.xsd”>
<cache name="tasks"
maxEntriesLocalHeap="200"
timeToLiveSeconds="600">
</cache>
package com.didi.controller;
import com.didi.SpringUtils;
import com.didi.domain.Man;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.inject.Inject;
@RestController
@Component
public class AopController {
/* @Inject
private SendEmailService sendEmailService;*/
@Inject
private HelloService helloService;
@RequestMapping("mail")
public String mail(){
System.out.println("可以成功访问-----------");
String result = helloService.hello(1);
System.out.println("获取结果" + result);
return "成功调用mail方法";
}
}
测试:
访问http://localhost:8080/mail
结果:
可以成功访问———–
没走缓存
获取结果没走缓存
可以成功访问———–
获取结果没走缓存
说明及原理:
第二次访问,没进入方法,这说明数据被缓存了,
Spring的缓存通过AOP的机制来实现,Spring将缓存实现为一个切面,每次访问先去缓存中取,取不到在进方法