tName(userReq.getName());
user.setId(Long.parseLong(userReq.getId()));
userService.updateById(user);
Map<String,String> result = new HashMap<String,String>();
result.put("respCode", "01");
result.put("respMsg", "更新成功");
return result;
}
@GetMapping("/get/{id}")
@ApiOperation(value="用户查询(ID)")
@ApiImplicitParam(name="id",value="查询ID",required=true)
@Cacheable(value="OKONG",key="#id")
public Map<String,Object> getUser(@PathVariable("id") String id){
//查询
User user = userService.selectById(id);
if(user == null) {
throw new CommonException("0001", "用户ID:" + id + ",未找到");
}
UserResp resp = UserResp.builder()
.id(user.getId().toString())
.code(user.getCode())
.name(user.getName())
.status(user.getStatus())
.build();
Map<String,Object> result = new HashMap<String,Object>();
result.put("respCode", "01");
result.put("respMsg", "成功");
result.put("data", resp);
return result;
}
@GetMapping("/page")
@ApiOperation(value="用户查询(分页)")
public Map<String,Object> pageUser(int current, int size){
//分页
Page<User> page = new Page<>(current, size);
Map<String,Object> result = new HashMap<String,Object>();
result.put("respCode", "01");
result.put("respMsg", "成功");
result.put("data", userService.selectPage(page));
return result;
}
}
2.利用Swagger
控制页面,新增一个用户,然后获取用户,会发现缓存里已经有此id的用户数据了。
第一次获取
redis查看:
redis
再次获取,会发现这次没有直接访问数据库了,而是直接从缓存读取。大家可在观察下控制台的输出情况(可先清空控制台,然后在请求)。
控制台
此时控制台无任何输出,但前端已经获取到值了。
关于SpringCache 注解的简单介绍
- @Cacheable:标记在一个方法上,也可以标记在一个类上。主要是缓存标注对象的返回结果,标注在方法上缓存该方法的返回值,标注在类上,缓存该类所有的方法返回值。
参数: value缓存名、 key缓存键值、 condition满足缓存条件、unless否决缓存条件
- @CachePut:方法支持缓存功能。与@Cacheable不同的是使用@CachePut标注的方法在执行前不会去检查缓存中是否存在之前执行过的结果,而是每次都会执行该方法,并将执行结果以键值对的形式存入指定的缓存中。
- @Caching:多个Cache注解使用,比如新增用户时,删除用户属性等需要删除或者更新多个缓存时,集合以上三个注解。
常用的就以上几个,对于@CacheConfig
没使用过,这里就不说明了。
对于对几个注解类的简单使用就结束了,相关的详细用法,比如自定义条件缓存,自定义注解等,这里就不阐述了,请读者自行
SpEL上下文数据
Spring Cache提供了一些供我们使用的SpEL上下文数据,下表直接摘自互联网:
名称 |
位置 |
描述 |
示例 |
methodName |
root对象 |
当前被调用的方法名 |
root.methodName |
method |
root对象 |
当前被调用的方法 |
root.method.name |
target |
root对象 |
当前被调用的目标对象 |
root.target |
targetClass |
root对象 |
当前被调用的目标对象类 |
root.targetClass |
args |
root对象 |
当前被调用的方法的参数列表 |
root.args[0] |
caches |
root对象 |
当前方法调用使用的缓存列表(如@Cacheable(value={“cache1”, “cache2”})),则有两个cache |
root.caches[0].name |
argument name |
执行上下文 |
当前被调用的方法的参数,如findById(Long id),我们可以通过#id拿到参数 |
user.id |
result |
执行上下文 |
方法执行后的返回值(仅当方法执行之后的判断有效,如‘unless’,’cache evict’的beforeInvocation=false) |
result |
@CacheEvict(value = "user", key = "#user.id", condition = "#root.target.canCache() and #root.caches[0].get(#user.id).get().username ne #user.username", beforeInvocation = true) public void conditionUpdate(User user)
总结
本章节主要是对redis
结合Spring Cache
的集成和简单使用进行了说明,详细的用法,可自行搜索相关资料下,这