ehcache 缓存使用
1配置类
@Configuration
@EnableCaching
public class EhcacheConfig {
@Bean(name = "appEhCacheCacheManager")
public EhCacheCacheManager ehCacheCacheManager(){
EhCacheManagerFactoryBean bean=ehCacheManagerFactoryBean();
return new EhCacheCacheManager (bean.getObject ());
}
@Bean
public EhCacheManagerFactoryBean ehCacheManagerFactoryBean(){
EhCacheManagerFactoryBean cacheManagerFactoryBean = new EhCacheManagerFactoryBean ();
cacheManagerFactoryBean.setConfigLocation (new ClassPathResource("ehcache.xml"));
cacheManagerFactoryBean.setShared (true);
return cacheManagerFactoryBean;
}
}
2调用service层
@Controller
@RequestMapping("/home/main")
public class HomeController {
@Autowired
HelloService helloService;
@RequestMapping("/show")
@ResponseBody
public String showHello(){
System.out.println(helloService.cacheService("1"));
System.out.println(helloService.cacheService("2"));
System.out.println(helloService.cacheService("1"));
System.out.println(helloService.cacheService("2"));
return rtn;
}
}
3service层方法加上@cacheable注解
@Service
public class HelloService {
@Cacheable(value = "helloworld", key="#id")
public String cacheService(String id){
System.out.println("excuteing blllaaaaaa");
return id+"_value";
}
}
4运行结果
excuteing blllaaaaaa
1_value
excuteing blllaaaaaa
2_value
1_value
2_value