一、几个重要缓存注解概念
Cache
缓存接口,定义缓存操作。实现有:RedisCache、EhCacheCache、 ConcurrentMapCache等
CacheManager
缓存管理器,管理各种缓存(Cache)组件
@Cacheable
主要针对方法配置,能够根据方法的请求参数对其结果进行缓存
@CacheEvict
清空缓存
@CachePut
保证方法被调用,又希望结果被缓存。
@EnableCaching
开启基于注解的缓存
keyGenerator
缓存数据时key生成策略
serialize
缓存数据时value序列化策略
1、pom.xml文件引入以下依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.1</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.46</version> </dependency>
2、application.properties文件配置如下:
spring.datasource.username=root spring.datasource.password=123456 spring.datasource.url=jdbc:mysql://localhost:3306/spring_cache spring.datasource.driver-class-name=com.mysql.jdbc.Driver #开启驼峰命名法 mybatis.configuration.map-underscore-to-camel-case=true #打印日志 logging.level.com.rf.springbootcache.mapper=debug三、建表语句如下:
1、创建员工表
CREATE TABLE `employee` ( `id` int(11) NOT NULL AUTO_INCREMENT, `lastName` varchar(255) DEFAULT NULL, `email` varchar(255) DEFAULT NULL, `gender` int(2) DEFAULT NULL, `d_id` int(11) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;四、缓存代码如下:
1、目录层次如下图:下面的所有操作都是在该目录结构中操作
2、在bean文件夹下创建Employee实体类,如下代码:
package com.rf.springbootcache.bean; public class Employee { private Integer id; //id private String lastName; //名字 private String email; //邮箱 private Integer gender; //性别 1男 0女 private Integer dId; //部门id public Employee() { super(); } public Employee(Integer id, String lastName, String email, Integer gender, Integer dId) { super(); this.id = id; this.lastName = lastName; this.email = email; this.gender = gender; this.dId = dId; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Integer getGender() { return gender; } public void setGender(Integer gender) { this.gender = gender; } public Integer getdId() { return dId; } public void setdId(Integer dId) { this.dId = dId; } @Override public String toString() { return "Employee [id=" + id + ", lastName=" + lastName + ", email=" + email + ", gender=" + gender + ", dId=" + dId + "]"; } }
3、在mapper文件夹下创建EmployeeMapper接口,如下代码:
package com.rf.springbootcache.mapper; import com.rf.springbootcache.bean.Employee; import org.apache.ibatis.annotations.*; @Mapper public interface EmployeeMapper { //根据id查询员工信息 @Select("select * from employee where id= #{id}") public Employee getEmpById(Integer id); //根据id修改员工信息 @Update("update employee set lastName=#{lastName},email=#{email},gender=#{gender},d_id=#{dId} where id=#{id}") public void updateEmp(Employee employee); //根据id删除员工信息 @Delete("delete from employee where id=#{id}") public void deleteEmpById(Integer id); //新增员工信息 @Insert("insert into employee(lastName,email,gender,d_id) values(#{lastName},#{email},#{gender},#{dId})") public void insertEmp(Employee employee); //根据名称查询员工信息 @Select("select * from employee where lastName= #{lastName}") public Employee getEmpByLastName(String lastName); }
4、在service文件夹下创建EmployeeService类,如下代码:
package com.rf.springbootcache.service; import com.rf.springbootcache.bean.Employee; import com.rf.springbootcache.mapper.EmployeeMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.*; import org.springframework.stereotype.Service; @CacheConfig(cacheNames="emp") //抽取缓存的公共配置 @Service public class EmployeeService { @Autowired EmployeeMapper employeeMapper; /** * @method 通过id查询员工信息方法 * * @Cacheable (在调用方法之前先调用缓存),将方法的运行结果进行缓存,以后再要相同的数据,直接从缓存中获取,不调用方法 * 属性: * cacheNames:指定缓存的组件的名字 * key:缓存数据使用的key;可以用它来指定。默认是使用方法参数的值 * keyGenerator:key的生成器;可以自己指定key的生成器的组件id * key/keyGenerator:二选一使用; * cacheManager:指定缓存管理器;或者cacheResolver指定获取解析器 * condition:指定符合条件的情况下才缓存;condition = "#a0>1":第一个参数的值》1的时候才进行缓存 * unless:否定缓存;unless = "#a0==2":如果第一个参数的值是2,结果不缓存; * sync:是否使用异步模式 * */ @Cacheable(value = {"emp"}/*,keyGenerator = "myKeyGenerator" ,condition = "#a0>1",unless = "#a0==2"*/) public Employee getEmpById(Integer id){ System.out.println("查询员工的id为:"+ id); Employee emp = employeeMapper.getEmpById(id); return emp; } /** * @method 修改员工信息方法 * @CachePut: 既调用方法,又更新缓存数据;同步更新缓存 * 修改了数据库的某个数据,同时更新缓存; * 运行时机: * 1、先调用目标方法 * 2、将目标方法的结果缓存起来 * * key = "#result.id":使用返回后的id */ @CachePut(/*value = "emp",*/key = "#result.id") public Employee updateEmp(Employee employee){ System.out.println("updateEmp:"+employee); employeeMapper.updateEmp(employee); return employee; } /** * @CacheEvict:缓存清除 * key:指定要清除的数据 * allEntries = true:指定清除这个缓存中所有的数据 * beforeInvocation = false:缓存的清除是否在方法之前执行 * 默认代表缓存清除操作是在方法执行之后执行;如果出现异常缓存就不会清除 * * beforeInvocation = true: * 代表清除缓存操作是在方法运行之前执行,无论方法是否出现异常,缓存都清除 */ @CacheEvict(/*value = "emp",*/key = "#id") public void deleteEmp(Integer id){ System.out.println("deleteEmp:"+id); // employeeMapper.deleteEmpById(id); } // @Caching 定义复杂的缓存规则 @Caching( cacheable = { @Cacheable(/*value="emp",*/key = "#lastName") }, put = { @CachePut(/*value="emp",*/key = "#result.id"), @CachePut(/*value="emp",*/key = "#result.email") } ) public Employee getEmpByLastName(String lastName){ return employeeMapper.getEmpByLastName(lastName); } }
5、在controller文件夹下创建EmployeeController类,如下代码:
package com.rf.springbootcache.controller; import com.rf.springbootcache.bean.Employee; import com.rf.springbootcache.service.EmployeeService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; @RestController public class EmployeeController { @Autowired EmployeeService employeeService; //根据id查询员工信息 @GetMapping("/emp/{id}") public Employee getEmpById(@PathVariable("id") Integer id){ Employee emp = employeeService.getEmpById(id); return emp; } //根据id修改员工信息 @GetMapping("/emp") public Employee updateEmp(Employee employee){ Employee employee1 = employeeService.updateEmp(employee); return employee1; } //根据id删除员工信息 @GetMapping("/delemp") public String delEmp(Integer id){ employeeService.deleteEmp(id); return "delete success"; } }四、@EnableCaching开启缓存和@MapperScan开启mybatis注解配置
1、SpringbootCacheApplication 启动类添加@EnableCaching开启缓存注解和@MapperScan开启mybatis注解配置,如下:
package com.rf.springbootcache; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cache.annotation.EnableCaching; @SpringBootApplication @MapperScan("com.rf.springbootcache.mapper") @EnableCaching //开启基于注解的缓存 public class SpringbootCacheApplication { public static void main(String[] args) { SpringApplication.run(SpringbootCacheApplication.class, args); } }五、启动springboot应用,访问查询方法
1、第一次查询控制台有日志输出,说明从数据库中获取数据,如下图:
2、清空控制台信息,再次刷新浏览器,查看控制台没有日志输出,说明从缓存中获取数据