springcache是spring3.1发布的使用注解去操作缓存的方法,解耦业务代码和缓存代码,在方法上使用注解就可以获取到缓存结果。
注意:
springcache只支持string类型不支持其他类型
springcache只支持单表查询不支持多表查询
常用注解
@CacheConfig(cacheNames = {"user"})
@Cacheable(key = "#id")
@CachePut(key = "#obj.id")
@CacheEvict(key = "#id")
@CacheConfig标注在类上标识缓存中的key都是以其中的value标识的
@Cacheable 标识在方法上当缓存中有数据的时候就会直接从缓存中获取,如果没有数据就会执行方法体然后将返回的数据存储在缓存中
@CachePut 在更改数据库的时候同时也更改缓存中的数据
@CacheEvice 在删除数据库的数据时也删除缓存中的数据
springcache提供了和事务兼容的性质当事务进行回滚的时候缓存也会进行回滚
demo:
Service
package com.qiqi.service;
import com.qiqi.entity.User;
import com.qiqi.mapper.UserMapper;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
/**
* Created By 丛梓祺 on 2021/10/25
* Write this code and change the world
*/
@Service
@CacheConfig(cacheNames = {"user"})
public class SpringCacheUserService {
@Autowired
private UserMapper userMapper;
/**
* 获取用户
*/
@Cacheable(key = "#id")
public User addUser(Integer id) {
return this.userMapper.selectByPrimaryKey(id);
}
@CachePut(key = "#obj.id")
public User updateUser(User obj){
this.userMapper.updateByPrimaryKeySelective(obj);
return this.userMapper.selectByPrimaryKey(obj.getId());
}
@CacheEvict(key = "#id")
public void deleteUser(Integer id){
User user=new User();
user.setId(id);
user.setDeleted((byte)1);
this.userMapper.updateByPrimaryKeySelective(user);
}
}
controller
package com.qiqi.controller;
import com.qiqi.entity.User;
import com.qiqi.service.SpringCacheUserService;
import org.springframework.web.bind.annotation.*;
/**
* Created By 丛梓祺 on 2021/10/25
* Write this code and change the world
*/
@RestController
@RequestMapping("/springCacheUsers")
public class SpringCacheUserController {
private final SpringCacheUserService userService;
public SpringCacheUserController(SpringCacheUserService userService) {
this.userService = userService;
}
@GetMapping(value = "/get/{id}")
public User getUser(@PathVariable("id") Integer id) {
return userService.addUser(id);
}
@PutMapping(value = "/put")
public void putUser( @RequestBody User user) {
userService.updateUser(user);
}
@DeleteMapping(value = "/del/{id}")
public void delUser(@PathVariable Integer id) {
userService.deleteUser(id);
}
}
验证结果
添加
可以看到service曾并没有写对于缓存的业务代码就可实现对缓存的操作
修改 更改了username
删除