简易博客点赞系统
好久没写 Java 了,整个简单的项目进行康复训练。
基于 Spring Boot + SSM + MySQL + Mybatis-Plus + Knife4j + Swagger 的一个简易博客点赞系统
开源地址:https://github.com/FangMoyu/simple-thumb
功能
- 登录
- 获取当前登录用户
- 获取博客
- 展示所有博客
- 点赞
- 取消点赞
亮点
- 基于编程式事务实现点赞和取消点赞功能
- 为避免用户重复点赞,使用本地锁对用户 id 进行加锁,防止接口短时间重复调用
- 提供了通用返回类、全局异常处理器、自定义错误码等
部分代码实现
点赞功能
@Override
public Boolean doThumb(DoThumbRequest doThumbRequest, HttpServletRequest request) {
// 参数校验
ThrowUtils.throwIf(doThumbRequest == null || doThumbRequest.getBlogId() == null,
ErrorCode.PARAMS_ERROR, "参数错误");
User loginUser = userService.getLoginUser(request);
// 加锁,避免用户短时间多次点赞
synchronized (loginUser.getId().toString().intern()) {
// 编程式事务
return transactionTemplate.execute(status -> {
// 获取当前当前进行点赞的博客id
Long blogId = doThumbRequest.getBlogId();
// 判断当前用户是否已经点赞过该博客
boolean exists = this.lambdaQuery()
.eq(Thumb::getBlogId, blogId)
.eq(Thumb::getUserId, loginUser.getId())
.exists();
// 如果已经点赞过,抛出异常
ThrowUtils.throwIf(exists, ErrorCode.OPERATION_ERROR, "已经点赞过");
// 更新博客点赞数 + 1
boolean update = blogService.lambdaUpdate()
.eq(Blog::getId, blogId)
.setSql("thumbCount = thumbCount + 1")
.update();
// 保存点赞记录
Thumb thumb = new Thumb();
thumb.setBlogId(blogId);
thumb.setUserId(loginUser.getId());
return update && this.save(thumb);
});
}
}
取消点赞
@Override
public Boolean undoThumb(DoThumbRequest doThumbRequest, HttpServletRequest request) {
// 参数校验
ThrowUtils.throwIf(doThumbRequest == null || doThumbRequest.getBlogId() == null, ErrorCode.PARAMS_ERROR, "参数错误");
User loginUser = userService.getLoginUser(request);
// 加锁,避免用户短时间多次取消点赞
synchronized (loginUser.getId().toString().intern()) {
// 编程式事务
return transactionTemplate.execute(status -> {
// 获取当前当前进行点赞的博客id
Long blogId = doThumbRequest.getBlogId();
// 判断当前用户是否已经点赞过该博客
Thumb thumb = this.lambdaQuery()
.eq(Thumb::getBlogId, blogId)
.eq(Thumb::getUserId, loginUser.getId())
.one();
// 如果没有点赞过,抛出异常
ThrowUtils.throwIf(thumb == null, ErrorCode.OPERATION_ERROR, "未点赞过");
// 更新博客点赞数 - 1
boolean update = blogService.lambdaUpdate()
.eq(Blog::getId, blogId)
.setSql("thumbCount = thumbCount - 1")
.update();
// 删除点赞记录
return update && this.removeById(thumb.getId());
});
}
}