完善评论模块

main
wangqing 12 months ago
parent abffc680cc
commit 731e12435b

@ -1,29 +0,0 @@
package com.luoo.comment.config;
import api.Result;
import api.StatusCode;
import com.luoo.comment.exception.AuthorityLoginException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
/**
*
*/
@Slf4j
@ControllerAdvice
public class BaseExceptionHandler {
@ExceptionHandler(value = Exception.class)
@ResponseBody
public Result<Void> error(Exception e) {
log.error("执行出错", e);
return Result.failed(StatusCode.MUSIC_COMMON_FAILED);
}
@ExceptionHandler(value = AuthorityLoginException.class)
@ResponseBody
public Result<String> error(AuthorityLoginException e) {
return Result.unauthorized(null);
}
}

@ -1,49 +0,0 @@
package com.luoo.comment.config;
import com.luoo.comment.constant.GlobalConstant;
import com.luoo.comment.utils.ThreadLocalMap;
import dto.UserLoginDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import util.JwtUtil;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Slf4j
@Component
public class TokenInterceptor implements HandlerInterceptor {
@Autowired
private JwtUtil jwtUtil;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
return HandlerInterceptor.super.preHandle(request, response, handler);
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
String token = request.getHeader("token");
UserLoginDto loginUser = jwtUtil.getUserLoginDto(token);
if (loginUser == null) {
log.error("获取用户信息失败, 不允许操作,需重新登录");
throw new RuntimeException("获取用户信息失败, 不允许操作,需重新登录");
}
log.info("请求uri => {} method => {} userId => {} token => {}",
request.getRequestURI(), request.getMethod(), loginUser.getUserId(),token);
ThreadLocalMap.put(GlobalConstant.TOKEN_AUTH_DTO, loginUser);
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
ThreadLocalMap.remove(GlobalConstant.TOKEN_AUTH_DTO);
}
}

@ -1,9 +0,0 @@
package com.luoo.comment.constant;
public class GlobalConstant {
/**
*
*/
public static final String TOKEN_AUTH_DTO = "CURRENT_USER_DTO";
}

@ -1,22 +0,0 @@
package com.luoo.comment.controller;
import cn.hutool.core.util.ObjectUtil;
import com.luoo.comment.exception.AuthorityLoginException;
import com.luoo.comment.utils.ThreadLocalMap;
import dto.UserLoginDto;
public class BaseController {
/**
*
*/
public static final String TOKEN_AUTH_DTO = "CURRENT_USER_DTO";
protected UserLoginDto getLoginAuthDto() {
UserLoginDto loginAuthDto = (UserLoginDto) ThreadLocalMap.get(TOKEN_AUTH_DTO);
if (ObjectUtil.isEmpty(loginAuthDto)) {
throw new AuthorityLoginException("登录信息已失效,请重新登录");
}
return loginAuthDto;
}
}

@ -6,70 +6,120 @@ import api.Result;
import api.StatusCode;
import com.luoo.comment.pojo.*;
import com.luoo.comment.service.CommentService;
import controller.BaseController;
import dto.UserLoginDto;
import io.swagger.models.auth.In;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.concurrent.TimeUnit;
@RestController
@CrossOrigin
@RequestMapping("/comment")
public class CommentController extends BaseController {
@Autowired
private CommentService commentService;
@GetMapping("/findByVolid/{volid}")
public Result<List<CommentVo>> findByVolid(@PathVariable String volid){
return Result.success(commentService.findByVolid(volid));
@Autowired
private RedisTemplate redisTemplate;
@GetMapping
public Result findAll(){
return Result.success(commentService.findAll());
}
/**
* ID parentID
*
* commentCount 280 @GetMapping("/comment/{parentId}/{page}/{size}")
*
* ,parentID2
* @return
*/
@GetMapping("/{journalId}/{page}/{size}")
public Result findAllByJournalId(@PathVariable String journalId,@PathVariable int page,@PathVariable int size) {
Page<Comment> pageData = commentService.findByJournalId(journalId,page,size);
return Result.success(new PageResult<Comment>(pageData.getTotalElements(),pageData.getContent()));
}
@GetMapping("/{commentId}")
public Result<Comment> findById(@PathVariable String commentId) {
public Result findById(@PathVariable String commentId){
return Result.success(commentService.findById(commentId));
}
@PostMapping("/save")
public Result<Void> save(@RequestBody CommentDto commentDto){
UserLoginDto loginAuthDto = getLoginAuthDto();
commentDto.setUserId(loginAuthDto.getUserId());
commentService.save(commentDto);
@PostMapping
public Result save(@RequestBody CommentVo commentVo, @RequestHeader(value = "Authorization", required = true) String authorization){
//验证是否登录并且拿到ID
UserLoginDto userLoginDto = getUserLoginDto(authorization);
if (null == userLoginDto) {
return Result.unauthorized(null);
}
String userId = userLoginDto.getUserId();
Comment comment = new Comment();
BeanUtils.copyProperties(commentVo, comment);
comment.setUserId(userId);
comment.setNickName(userLoginDto.getNickName());
commentService.save(comment);
return Result.success();
}
@PutMapping("/{commentId}")
public Result update(@PathVariable String commentId,@RequestBody Comment comment) {
comment.set_id(commentId);
commentService.update(comment);
return Result.success();
}
@DeleteMapping("/{commentId}")
public Result<Void> delete(@PathVariable String commentId){
public Result delete(@PathVariable String commentId) {
commentService.deleteById(commentId);
return Result.success();
}
@GetMapping("/findByParentId")
public Result<PageResult<CommentVo>> findByParentId(@RequestParam String parentId,
@RequestParam int page,
@RequestParam int size){
Page<CommentVo> pageData = commentService.findByParentId(parentId,page,size);
return Result.success(new PageResult<>(pageData.getTotalElements(),pageData.getContent()));
@GetMapping("/comment/{parentId}/{page}/{size}")
public Result findByParentId(@PathVariable String parentId,@PathVariable int page,@PathVariable int size) {
Page<Comment> pageData = commentService.findByParentId(parentId,page,size);
return Result.success(new PageResult<Comment>(pageData.getTotalElements(),pageData.getContent()));
}
@PutMapping("/thumbup")
public Result thumbup(@RequestBody CommentThumbupDto commentThumbupDto){
UserLoginDto loginAuthDto = getLoginAuthDto();
String userId = loginAuthDto.getUserId();
commentThumbupDto.setUserId(userId);
commentService.thumbup(commentThumbupDto);
return Result.success();
@PutMapping("/thumbup/{commentId}")
public Result thumbup(@PathVariable String commentId,@RequestHeader(value = "Authorization", required = true) String authorization) {
// 判断当前用户是否已经点赞
//验证是否登录并且拿到ID
UserLoginDto userLoginDto = getUserLoginDto(authorization);
if (null == userLoginDto) {
return Result.unauthorized(null);
}
String userId = userLoginDto.getUserId();
@GetMapping("/getUserCommentInfo")
public Result<CommentThumbupVo> getUserCommentInfo(@RequestParam String userId){
CommentThumbupVo userCommentInfo = commentService.getUserCommentInfo(userId);
return Result.success(userCommentInfo);
if(redisTemplate.opsForValue().get("thumbup_"+commentId+"_"+userId)!=null){
return Result.failed(StatusCode.COMMENT_REPEAT_THUMBUP);
}
commentService.thumbup(commentId);
redisTemplate.opsForValue().set("thumbup_"+commentId+"_"+userId,1,10, TimeUnit.SECONDS);
return Result.success();
}
}

@ -5,12 +5,8 @@ import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.repository.MongoRepository;
import java.util.List;
public interface CommentDao extends MongoRepository<Comment,String> {
Page<Comment> findByParentId(String parentId, Pageable pageable);
List<Comment> findByArticleId(String articleId);
public Page<Comment> findByParentId(String parentId, Pageable pageable);
public Page<Comment> findByJournalId(String journalId, Pageable pageable);
}

@ -1,29 +0,0 @@
package com.luoo.comment.enums;
public enum CommentStatusEnum {
/**
*
*/
NORMAL(1),
/**
*
*/
DELETE(2),
/**
*
*/
AUDITING(3);
private final int value;
CommentStatusEnum(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}

@ -1,64 +0,0 @@
package com.luoo.comment.enums;
import cn.hutool.core.util.ObjectUtil;
public enum Province {
BEIJING("Beijing", "北京"),
TIANJIN("Tianjin", "天津"),
SHANGHAI("Shanghai", "上海"),
CHONGQING("Chongqing", "重庆"),
HEBEI("Hebei", "河北"),
SHANXI("Shanxi", "山西"),
LIAONING("Liaoning", "辽宁"),
JILIN("Jilin", "吉林"),
HEILONGJIANG("Heilongjiang", "黑龙江"),
JIANGSU("Jiangsu", "江苏"),
ZHEJIANG("Zhejiang", "浙江"),
ANHUI("Anhui", "安徽"),
FUJIAN("Fujian", "福建"),
JIANGXI("Jiangxi", "江西"),
SHANDONG("Shandong", "山东"),
HENAN("Henan", "河南"),
HUBEI("Hubei", "湖北"),
HUNAN("Hunan", "湖南"),
GUANGDONG("Guangdong", "广东"),
GUANGXI("Guangxi", "广西"),
HAINAN("Hainan", "海南"),
SICHUAN("Sichuan", "四川"),
GUIZHOU("Guizhou", "贵州"),
YUNNAN("Yunnan", "云南"),
TIBET("Tibet", "西藏"),
SHAANXI("Shaanxi", "陕西"),
GANSU("Gansu", "甘肃"),
QINGHAI("Qinghai", "青海"),
NINGXIA("Ningxia", "宁夏"),
XINJIANG("Xinjiang", "新疆");
private final String englishName;
private final String chineseName;
Province(String englishName, String chineseName) {
this.englishName = englishName;
this.chineseName = chineseName;
}
public String getEnglishName() {
return englishName;
}
public String getChineseName() {
return chineseName;
}
public static String getCityName(String englishName) {
if (ObjectUtil.isEmpty(englishName)) {
return "未知IP";
}
for (Province province : Province.values()) {
if (englishName.equalsIgnoreCase(province.englishName)) {
return province.chineseName;
}
}
return "未知IP";
}
}

@ -1,24 +0,0 @@
package com.luoo.comment.enums;
public enum ThumbupActionEnum {
/**
*
*/
CONFIRM(1),
/**
*
*/
CANCEL(0);
private final int value;
ThumbupActionEnum(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}

@ -1,40 +0,0 @@
package com.luoo.comment.exception;
import api.StatusCode;
public class AuthorityLoginException extends RuntimeException {
private static final long serialVersionUID = 2466145171145432619L;
private StatusCode codeEnum;
private Integer code = 401;
public AuthorityLoginException(String message) {
super(message);
}
public AuthorityLoginException(String message, Integer code) {
super(message);
this.code = code;
}
public StatusCode getCodeEnum() {
return codeEnum;
}
public Integer getCode() {
return this.code;
}
public AuthorityLoginException(StatusCode codeEnum) {
super(codeEnum.getMessage());
this.codeEnum = codeEnum;
this.code = codeEnum.getCode();
}
/**
* fillInStackTrace .
*/
@Override
public Throwable fillInStackTrace() {
return this;
}
}

@ -1,17 +1,17 @@
package com.luoo.comment.pojo;
import lombok.Data;
import org.springframework.beans.BeanUtils;
import org.springframework.data.annotation.Id;
import java.io.Serializable;
import java.util.Date;
@Data
public class Comment implements Serializable {
@Id
private String id;
private String _id;
// 评论内容
private String content;
// 发布时间
@ -19,12 +19,14 @@ public class Comment implements Serializable {
private String userId;
private String nickName;
// 点赞数
private Integer thumbup;
private Integer thumbupCount;
// 转发数
private Integer share;
// private Integer share;
// 评论数量
private Integer comment;
private Integer commentCount;
// 状态
private Integer state;
@ -34,23 +36,5 @@ public class Comment implements Serializable {
*/
private String parentId;
private String articleId;
private Integer level;
private String targetId;
/**
*
*/
private Integer type;
private String city;
public CommentVo convertVo () {
CommentVo commentVo = new CommentVo();
BeanUtils.copyProperties(this, commentVo);
return commentVo;
}
private String journalId;
}

@ -1,37 +0,0 @@
package com.luoo.comment.pojo;
import lombok.Data;
import java.io.Serializable;
@Data
public class CommentDto implements Serializable {
/**
* ID
*/
private String articleId;
/**
*
*/
private String content;
/**
* ID
*/
private String parentId;
/**
* ID
*/
private String targetId;
/**
* IP
*/
private String ipAddress;
private String userId;
}

@ -1,19 +0,0 @@
package com.luoo.comment.pojo;
import lombok.Data;
import javax.validation.constraints.NotNull;
/**
* DTO
*/
@Data
public class CommentThumbupDto {
@NotNull
private String commentId;
private Integer action;
private String userId;
}

@ -1,23 +0,0 @@
package com.luoo.comment.pojo;
import lombok.Data;
@Data
public class CommentThumbupVo {
/**
*
*/
private Long thumbupNum;
/**
*
*/
private Long commentNum;
/**
* ID
*/
private String userId;
}

@ -2,77 +2,16 @@ package com.luoo.comment.pojo;
import lombok.Data;
import java.util.Date;
@Data
public class CommentVo {
private String id;
/**
*
*/
// 评论内容
private String content;
/**
*
*/
private Date publishTime;
/**
* ID
*/
private String userId;
/**
*
*/
private String nickName;
/**
*
*/
private Integer thumbup;
/**
*
*/
private Integer share;
/**
*
*/
private Integer comment;
/**
*
*/
private String state;
/**
* ID
*/
private String parentId;
/**
*
*/
private String articleId;
/**
*
*/
private Integer level;
/**
* ID
*/
private String targetId;
/**
*
*/
private CommentVo targetComment;
/**
*
*/
private String type;
/**
*
*/
private String city;
private String journalId;
}

@ -1,29 +1,96 @@
package com.luoo.comment.service;
import com.luoo.comment.pojo.*;
import com.luoo.comment.dao.CommentDao;
import com.luoo.comment.pojo.Comment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import util.IdWorker;
import java.util.Date;
import java.util.List;
public interface CommentService {
@Service
@Transactional
public class CommentService {
Comment findById(String id);
@Autowired
private CommentDao commentDao;
void save(CommentDto commentDto);
@Autowired
private IdWorker idWorker;
void update(Comment comment);
@Autowired
private MongoTemplate mongoTemplate;
void deleteById(String id);
@Autowired
Page<CommentVo> findByParentId(String parentId, int page, int size);
public List<Comment> findAll(){
return commentDao.findAll();
}
public Comment findById(String id) {
return commentDao.findById(id).get();
}
public void save(Comment comment) {
comment.set_id(idWorker.nextId()+"");
comment.setPublishTime(new Date());
comment.setThumbupCount(0); //点赞数
comment.setCommentCount(0); //回复数
comment.setState(1);
// 如果当前添加的评论,有父节点,那么父节点的评论回复数要加一
if (comment.getParentId()!=null && !"".equals(comment.getParentId())){
comment.setJournalId("");//如果有父节点,将期刊号置为空
Query query = new Query();
query.addCriteria(Criteria.where("_id").is(comment.getParentId()));
Update update = new Update();
update.inc("commentCount",1);
mongoTemplate.updateFirst(query,update,"comment");
}
commentDao.save(comment);
}
public void update (Comment comment) {
commentDao.save(comment);
}
void thumbup(CommentThumbupDto commentThumbupDto);
List<CommentVo> findByVolid(String volid);
public void deleteById(String id) {
commentDao.deleteById(id);
}
public Page<Comment> findByParentId(String parentId, int page, int size) {
Pageable pageable = PageRequest.of(page-1,size);
return commentDao.findByParentId(parentId,pageable);
}
/**
*
*/
CommentThumbupVo getUserCommentInfo(String userId);
public Page<Comment> findByJournalId(String journalId, int page, int size) {
Pageable pageable = PageRequest.of(page-1,size);
return commentDao.findByJournalId(journalId,pageable);
}
public void thumbup(String commentId) {
Query query = new Query();
query.addCriteria(Criteria.where("_id").is(commentId));
Update update = new Update();
update.inc("thumbupCount",1);
mongoTemplate.updateFirst(query,update,"comment");
}
}

@ -1,233 +0,0 @@
package com.luoo.comment.service.impl;
import api.Result;
import client.vo.SimpleUser;
import cn.hutool.core.util.ObjectUtil;
import com.luoo.comment.dao.CommentDao;
import com.luoo.comment.enums.CommentStatusEnum;
import com.luoo.comment.enums.Province;
import com.luoo.comment.enums.ThumbupActionEnum;
import com.luoo.comment.pojo.*;
import com.luoo.comment.service.CommentService;
import lombok.extern.slf4j.Slf4j;
import net.renfei.ip2location.IP2Location;
import net.renfei.ip2location.IPResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import util.IdWorker;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
@Service
@Transactional
@Slf4j
public class CommentServiceImpl implements CommentService {
// @Autowired
// private UserClient userClient;
@Autowired
private CommentDao commentDao;
@Autowired
private IdWorker idWorker;
@Autowired
private MongoTemplate mongoTemplate;
@Autowired
private RedisTemplate redisTemplate;
public Comment findById(String id) {
return commentDao.findById(id).get();
}
public String getCityNameByIp(String ip) {
IP2Location loc = new IP2Location();
String binFile = "classpath:/IP2LOCATION-LITE-DB11.BIN";
try {
loc.Open(binFile, true);
IPResult rec = loc.IPQuery(ip);
String city = rec.getCity();
return Province.getCityName(city);
} catch (IOException e) {
log.info("getCityNameByIp error {}",ip,e);
return "未知 IP";
}
}
public void save(CommentDto commentDto){
Comment comment = new Comment();
comment.setContent(commentDto.getContent());
comment.setPublishTime(new Date());
comment.setUserId(commentDto.getUserId());
comment.setComment(0);
comment.setParentId(commentDto.getParentId());
comment.setArticleId(commentDto.getArticleId());
comment.setLevel(1);
comment.setTargetId(commentDto.getTargetId());
comment.setType(0);
comment.setCity(getCityNameByIp(commentDto.getIpAddress()));
comment.setId(String.valueOf(idWorker.nextId()));
comment.setShare(0);
comment.setThumbup(0);
comment.setComment(0);
comment.setState(CommentStatusEnum.NORMAL.getValue());
// 如果当前添加的吐槽,有父节点,那么父节点的吐槽回复数要加一
if (ObjectUtil.isNotEmpty(comment.getParentId())) {
// 更新父节点的评论回复数
Query query = new Query();
query.addCriteria(Criteria.where("_id").is(comment.getParentId()));
Update update = new Update();
update.inc("comment",1);
mongoTemplate.updateFirst(query,update,Comment.class);
}
if (ObjectUtil.isNotEmpty(comment.getTargetId())) {
Comment parentIdComment = mongoTemplate.findById(comment.getTargetId(), Comment.class);
comment.setLevel(parentIdComment.getLevel()+1);
Query query = new Query();
query.addCriteria(Criteria.where("_id").is(comment.getTargetId()));
Update update = new Update();
update.inc("comment",1);
mongoTemplate.updateFirst(query,update,Comment.class);
}
commentDao.save(comment);
}
public void update(Comment comment) {
commentDao.save(comment);
}
public void deleteById(String id) {
commentDao.deleteById(id);
}
public Page<CommentVo> findByParentId(String parentId,int page,int size){
Pageable pageable = PageRequest.of(page, size);
Query query = new Query();
Criteria criteria = Criteria.where("parentId").is(parentId);
query.addCriteria(criteria);
Sort sort = Sort.by(Sort.Direction.ASC, "age");
query.with(sort);
query.with(pageable);
List<Comment> comments = mongoTemplate.find(query, Comment.class);
List<String> userIds = comments.stream().map(Comment::getUserId).collect(Collectors.toList());
// Result<List<SimpleUser>> userByIds = userClient.findUserByIds(userIds);
Result<List<SimpleUser>> userByIds = Result.success(null);
Map<String, SimpleUser> userIdAndInfoMap = userByIds.getData().stream().collect(Collectors.toMap(SimpleUser::getUserId, Function.identity()));
List<CommentVo> commentVos = comments.stream().map(Comment::convertVo).collect(Collectors.toList());
// List<String> targetComments = comments.stream().map(Comment::getTargetId).collect(Collectors.toList());
Map<String, CommentVo> idCommentMap = commentVos.stream().collect(Collectors.toMap(CommentVo::getId, Function.identity()));
long total = mongoTemplate.count(query, Comment.class);
// boolean isChange = targetComments.removeAll(idCommentMap.keySet());
for (CommentVo commentVo : commentVos) {
// 处理昵称
SimpleUser simpleUser = userIdAndInfoMap.get(commentVo.getUserId());
if (ObjectUtil.isNotEmpty(simpleUser)) {
commentVo.setNickName(simpleUser.getNickName());
}
// 处理叠楼评论回复
if (commentVo.getLevel() > 2 && ObjectUtil.isNotEmpty(commentVo.getTargetId())) {
CommentVo targetCommentVo = idCommentMap.get(commentVo.getTargetId());
if (targetCommentVo != null) {
commentVo.setTargetComment(targetCommentVo);
}
}
}
return new PageImpl<>(commentVos, pageable, total);
}
public void thumbup(CommentThumbupDto commentThumbupDto) {
String userId = commentThumbupDto.getUserId();
Long count = (Long)redisTemplate.opsForValue().get("thumbup_" + userId);
Query query = new Query();
query.addCriteria(Criteria.where("_id").is(commentThumbupDto.getCommentId()));
Update update = new Update();
if (commentThumbupDto.getAction().equals(ThumbupActionEnum.CONFIRM.getValue())) {
update.inc("thumbup",1);
if (ObjectUtil.isNotEmpty(count)) {
redisTemplate.opsForValue().set("thumbup_"+userId,++count);
} else {
redisTemplate.opsForValue().set("thumbup_"+userId,1L);
}
} else {
update.inc("thumbup",-1);
}
mongoTemplate.updateFirst(query,update,Comment.class);
}
public List<CommentVo> findByVolid(String volid) {
List<Comment> byArticleId = commentDao.findByArticleId(volid);
if (ObjectUtil.isEmpty(byArticleId)) {
return new ArrayList<>();
}
List<CommentVo> commentVos = byArticleId.stream().map(Comment::convertVo).collect(Collectors.toList());
List<String> userIds = byArticleId.stream().map(Comment::getUserId).collect(Collectors.toList());
// Result<List<SimpleUser>> userByIds = userClient.findUserByIds(userIds);
Result<List<SimpleUser>> userByIds = Result.success(null);
Map<String, SimpleUser> userIdAndInfoMap = userByIds.getData().stream().collect(Collectors.toMap(SimpleUser::getUserId, Function.identity()));
for (CommentVo commentVo : commentVos) {
// 处理昵称
SimpleUser simpleUser = userIdAndInfoMap.get(commentVo.getUserId());
if (ObjectUtil.isNotEmpty(simpleUser)) {
commentVo.setNickName(simpleUser.getNickName());
}
}
return commentVos;
}
@Override
public CommentThumbupVo getUserCommentInfo(String userId) {
// 获取用户点赞数量
CommentThumbupVo commentThumbupVo = new CommentThumbupVo();
Long count = (Long)redisTemplate.opsForValue().get("thumbup_" + userId);
if (ObjectUtil.isEmpty(count)) {
count = 0L;
}
commentThumbupVo.setThumbupNum(count);
// 获取评论数量
Query query = new Query();
query.addCriteria(Criteria.where("userId").is(userId));
long commentCount = mongoTemplate.count(query, Comment.class);
commentThumbupVo.setCommentNum(commentCount);
return commentThumbupVo;
}
}

@ -1,84 +0,0 @@
package com.luoo.comment.utils;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import java.util.HashMap;
import java.util.Map;
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class ThreadLocalMap {
/**
* The constant threadContext.
*/
private final static ThreadLocal<Map<String, Object>> THREAD_CONTEXT = new MapThreadLocal();
/**
* Put.
*
* @param key the key
* @param value the value
*/
public static void put(String key, Object value) {
getContextMap().put(key, value);
}
/**
* Remove object.
*
* @param key the key
*
* @return the object
*/
public static Object remove(String key) {
return getContextMap().remove(key);
}
/**
* Get object.
*
* @param key the key
*
* @return the object
*/
public static Object get(String key) {
return getContextMap().get(key);
}
private static class MapThreadLocal extends ThreadLocal<Map<String, Object>> {
/**
* Initial value map.
*
* @return the map
*/
@Override
protected Map<String, Object> initialValue() {
return new HashMap<String, Object>(8) {
private static final long serialVersionUID = 3637958959138295593L;
@Override
public Object put(String key, Object value) {
return super.put(key, value);
}
};
}
}
/**
* thread context Map
*
* @return thread context Map
*/
private static Map<String, Object> getContextMap() {
return THREAD_CONTEXT.get();
}
/**
* 线hold便
*/
public static void remove() {
getContextMap().clear();
}
}

@ -26,6 +26,7 @@ public enum StatusCode implements IErrorCode {
// comment 模块错误码以30XXX不足5位补0;
COMMENT_COMMON_FAILED(30000, "评论模块错误"),
COMMENT_REPEAT_SUBMIT(30001, "评论重复提交"),
COMMENT_REPEAT_THUMBUP(30002,"不能重复点赞"),
// friend 模块错误码以40XXX不足5位补0;
FRIEND_COMMON_FAILED(40000, "交友模块错误"),

Loading…
Cancel
Save