这几天在开发的项目中,考虑引入一些缓存机制。顺便又了解了一下spring-boot的缓存、以及JSR107、ehcache。并做了一些使用实例。
spring-boot缓存使用实例
spring-boot中引入依赖spring-boot-starter-cache
,pom.xml:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
/**
* 启动类
*/
@SpringBootApplication
@EnableAutoConfiguration
@EnableCaching // 启用缓存
public class Application extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}
public static void main(String[] args) throws Exception {
SpringApplication.run(Application.class, args);
}
}
/**
* restful类
*/
@RestController
public class SampleController {
@Autowired
private SampleServiceImpl sampleService;
@RequestMapping("/sample/test")
public BaseQueryParam test(BaseQueryParam dto) {
return sampleService.testCache(dto);
}
}
@Service
public class SampleServiceImpl {
// 取第一个参数可以用这几种姿势#root.args[1]或#p0或#a0
@Cacheable(value="SampleServiceImpl", key="#p0.resourceId")
public BaseQueryParam testCache(BaseQueryParam param) {
System.out.println("第1次访问时未缓存,打印此文本");
return param;
}
}
public class BaseQueryParam {
/**
* 资源标识。主要用来标识需要访问的资源类型
*/
private String resourceId;
public String getResourceId() {
return resourceId;
}
public void setResourceId(String resourceId) {
this.resourceId = resourceId;
}
}
测试: