Spring Boot 对 Cache 提供了良好的支持,可以通过注解为程序添加缓存 Cache 功能。
本文中使用 Spring Boot 构建Rest服务实验手册(一) 中的案例演示缓存(Cache)功能。
添加依赖
依赖库
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency> <dependency> <groupId>javax.cache</groupId> <artifactId>cache-api</artifactId> <version>1.1.0</version> </dependency> <dependency> <groupId>org.ehcache</groupId> <artifactId>ehcache</artifactId> <version>3.6.2</version> </dependency>
|
定义缓存
在 application.yml 文件中定义缓存,新增加一个cache-names定义:
1 2 3
| spring: cache: cache-names: todos
|
改造缓存对象
需要缓存对象需要实现可序列化接口: Serializable
我们使用案例中的 Todo 对象作为缓存对象。 代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| @Data @AllArgsConstructor @NoArgsConstructor @Entity @ApiModel(description = "All details about the Todo.") public class Todo implements Serializable {
@Id @GeneratedValue(strategy= GenerationType.AUTO) @ApiModelProperty(notes = "唯一编码,有系统自动生成") private Integer id;
@NotNull private String title;
private String desc; }
|
添加缓存功能(Cache)
在案例中,我们为业务类: TodoBiz 中的 getByTitle 方法增加缓存功能。更改后的代码如下:
1 2 3 4 5 6
| @Transactional @Cacheable(value="todos", key="#title") public List<Todo> getByTitle(String title) {
return todoRepository.findByTitle(title); }
|
为应用启动缓存(Cache)
在应用启动类: TodoApiApplication 上加入注解以启动缓存功能:
1 2 3 4 5 6 7 8 9 10 11
| @SpringBootApplication @EnableSwagger2 @EnableCaching public class TodoApiApplication {
public static void main(String[] args) {
SpringApplication.run(TodoApiApplication.class, args); }
}
|
验证缓存
启动应用,使用浏览器访问:
1
| http://localhost:8080/todo/getByTitle
|
可以得到类似的结果:
1
| {"succ":true,"code":null,"msg":null,"data":[{"id":33,"title":"jack","desc":"Desc for new 1"}]}
|
观察后台日志,可以看到执行了 SQL 查询语句(select)。
再次刷新网址,可以看到浏览器显示相同的结果,但后台不会在执行新的SQL语句。