一.代码示例
1.pom配置坐标
< dependency>
< groupId> org. springframework. boot< / groupId>
< artifactId> spring- boot- starter- cache< / artifactId>
< / dependency>
< ! -- mysql -- >
< dependency>
< groupId> mysql< / groupId>
< artifactId> mysql- connector- java< / artifactId>
< / dependency>
< ! -- mybatis- plus-- >
< dependency>
< groupId> com. baomidou< / groupId>
< artifactId> mybatis- plus- boot- starter< / artifactId>
< version> 3.4 .2 < / version>
< / dependency>
2.application配置
spring :
datasource :
url : jdbc: mysql: / / localhost: 3306 / test? serverTimezone= UTC & useUnicode= true & characterEncoding= utf- 8 & useSSL= false
driver- class - name: com. mysql. cj. jdbc. Driver
username : root
password : root
mybatis- plus:
global- config:
db- config:
table- prefix: learning_
id- type: auto
configuration :
log- impl: org. apache. ibatis. logging. stdout. StdOutImpl
3.启用缓存
package com. learning;
import org. springframework. boot. SpringApplication;
import org. springframework. boot. autoconfigure. SpringBootApplication;
import org. springframework. cache. annotation. EnableCaching;
@SpringBootApplication
@EnableCaching
public class SpringBootLearningApplication {
public static void main ( String[ ] args ) {
SpringApplication. run ( SpringBootLearningApplication. class, args) ;
}
}
4.controller
package com. learning. controller;
import com. learning. domain. Student;
import com. learning. service. StudentService;
import lombok. AllArgsConstructor;
import org. springframework. beans. factory. annotation. Autowired;
import org. springframework. web. bind. annotation. GetMapping;
import org. springframework. web. bind. annotation. RequestMapping;
import org. springframework. web. bind. annotation. RestController;
@RestController
@RequestMapping ( "/cache" )
@AllArgsConstructor
public class CacheController {
private StudentService studentService;
@GetMapping ( "/get" )
public Student get ( String id) {
return studentService. getById ( id) ;
}
}
5.service
1. @Cacheable既会存,也会取
2. @CachePut只会存,不会取
package com. learning. service. impl;
import com. learning. dao. StudentDao;
import com. learning. domain. Student;
import com. learning. service. StudentService;
import lombok. AllArgsConstructor;
import org. springframework. cache. annotation. Cacheable;
import org. springframework. stereotype. Service;
@Service
@AllArgsConstructor
public class StudentServiceImpl implements StudentService {
private StudentDao studentDao;
@Override
@Cacheable ( value= "studentCache" , key= "#id" )
public Student getById ( String id ) {
return studentDao. selectById ( id) ;
}
}
6.dao
package com. learning. dao;
import com. baomidou. mybatisplus. core. mapper. BaseMapper;
import com. learning. domain. Student;
import org. apache. ibatis. annotations. Mapper;
@Mapper
public interface StudentDao extends BaseMapper < Student> {
}
二.效果示例
1. 查询两次接口,只会查询一次日志
2. 数据库截图