提交 7fe49d9d authored 作者: 吴德鹏's avatar 吴德鹏

商品评论优化

上级 b2a953cb
...@@ -61,5 +61,7 @@ public class KeyConstant { ...@@ -61,5 +61,7 @@ public class KeyConstant {
public final static String VISIT_COUNT="visit_count"; public final static String VISIT_COUNT="visit_count";
public final static String ITEM_LIKE="item_like:";
} }
...@@ -11,6 +11,7 @@ import org.springframework.data.redis.core.RedisTemplate; ...@@ -11,6 +11,7 @@ import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations; import org.springframework.data.redis.core.SetOperations;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import java.time.Duration;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
...@@ -42,6 +43,26 @@ public class RedisCache<T> { ...@@ -42,6 +43,26 @@ public class RedisCache<T> {
} }
public Long incr(String key) {
logger.debug("incr key [{}]", key);
try {
return redisTemplate.opsForValue().increment(key);
} catch (Throwable t) {
logger.error("set key [{}] exception!", key, t);
throw new CacheException(t);
}
}
public Long decr(String key) {
logger.debug("incr key [{}]", key);
try {
return redisTemplate.opsForValue().decrement(key);
} catch (Throwable t) {
logger.error("set key [{}] exception!", key, t);
throw new CacheException(t);
}
}
public T set(String key, T value) { public T set(String key, T value) {
logger.debug("set key [{}]", key); logger.debug("set key [{}]", key);
try { try {
...@@ -64,6 +85,28 @@ public class RedisCache<T> { ...@@ -64,6 +85,28 @@ public class RedisCache<T> {
} }
} }
public Boolean setNx(String key, T value, long timeout) {
logger.debug("set key [{}]", key);
try {
Boolean exist = redisTemplate.opsForValue().setIfAbsent(key, value, timeout, TimeUnit.SECONDS);
return exist;
} catch (Throwable t) {
logger.error("set key [{}] exception!", key, t);
throw new CacheException(t);
}
}
public Boolean setNx(String key, T value) {
logger.debug("set key [{}]", key);
try {
Boolean exist = redisTemplate.opsForValue().setIfAbsent(key, value);
return exist;
} catch (Throwable t) {
logger.error("set key [{}] exception!", key, t);
throw new CacheException(t);
}
}
public void delete(String key) { public void delete(String key) {
logger.debug("delete key [{}]", key); logger.debug("delete key [{}]", key);
try { try {
......
package com.example.afrishop_v3.controllers; package com.example.afrishop_v3.controllers;
import com.example.afrishop_v3.base.Result; import com.example.afrishop_v3.base.Result;
import com.example.afrishop_v3.bo.KeyConstant;
import com.example.afrishop_v3.config.RedisCache;
import com.example.afrishop_v3.enums.ResultCodeEnum; import com.example.afrishop_v3.enums.ResultCodeEnum;
import com.example.afrishop_v3.models.*; import com.example.afrishop_v3.models.*;
import com.example.afrishop_v3.repository.*; import com.example.afrishop_v3.repository.*;
import com.example.afrishop_v3.security.services.AuthenticationUser;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
...@@ -31,9 +34,11 @@ public class ItemController { ...@@ -31,9 +34,11 @@ public class ItemController {
private final TbCfItemParamRepository itemParamRepository; private final TbCfItemParamRepository itemParamRepository;
private final TbCfRecommendRepository recommendRepository; private final TbCfRecommendRepository recommendRepository;
private final TbCfItemCommentRepository commentRepository; private final TbCfItemCommentRepository commentRepository;
private final AuthenticationUser user;
private final RedisCache redisCache;
private static Logger logger = LoggerFactory.getLogger(ItemController.class); private static Logger logger = LoggerFactory.getLogger(ItemController.class);
public ItemController(TbCfStationItemRepository repository, TbCfGoodstwotypeRepository goodstwotypeRepository, TbCfGoodstypeRepository goodstypeRepository, TbCfDescripitonRepository descriptionRepository, TbCfCategoryRepository categoryRepository, TbCfItemSkuRepository skuRepository, TbCfItemDescRepository descRepository, TbCfItemCollectionRepository collectionRepository, TbCfItemParamRepository itemParamRepository, TbCfRecommendRepository recommendRepository, TbCfItemCommentRepository commentRepository) { public ItemController(TbCfStationItemRepository repository, TbCfGoodstwotypeRepository goodstwotypeRepository, TbCfGoodstypeRepository goodstypeRepository, TbCfDescripitonRepository descriptionRepository, TbCfCategoryRepository categoryRepository, TbCfItemSkuRepository skuRepository, TbCfItemDescRepository descRepository, TbCfItemCollectionRepository collectionRepository, TbCfItemParamRepository itemParamRepository, TbCfRecommendRepository recommendRepository, TbCfItemCommentRepository commentRepository, AuthenticationUser user, RedisCache redisCache) {
this.repository = repository; this.repository = repository;
this.goodstwotypeRepository = goodstwotypeRepository; this.goodstwotypeRepository = goodstwotypeRepository;
this.goodstypeRepository = goodstypeRepository; this.goodstypeRepository = goodstypeRepository;
...@@ -45,6 +50,8 @@ public class ItemController { ...@@ -45,6 +50,8 @@ public class ItemController {
this.itemParamRepository = itemParamRepository; this.itemParamRepository = itemParamRepository;
this.recommendRepository = recommendRepository; this.recommendRepository = recommendRepository;
this.commentRepository = commentRepository; this.commentRepository = commentRepository;
this.user = user;
this.redisCache = redisCache;
} }
@GetMapping("/queryAll") @GetMapping("/queryAll")
...@@ -221,7 +228,7 @@ public class ItemController { ...@@ -221,7 +228,7 @@ public class ItemController {
} }
@GetMapping("/queryItemComments") @GetMapping("/queryItemComments")
public Result queryItemLastComment( public Result queryItemComments(
@RequestParam("itemId") String itemId, @RequestParam("itemId") String itemId,
@RequestParam(value = "pageNum", defaultValue = "0") Integer pageNum, @RequestParam(value = "pageNum", defaultValue = "0") Integer pageNum,
@RequestParam(value = "pageSize", defaultValue = "6") Integer pageSize, @RequestParam(value = "pageSize", defaultValue = "6") Integer pageSize,
...@@ -233,17 +240,67 @@ public class ItemController { ...@@ -233,17 +240,67 @@ public class ItemController {
return result; return result;
} }
// try { try {
Page<TbCfItemComment> allByItemId = commentRepository.findAllByItemId(itemId, PageRequest.of(pageNum, pageSize,Sort.by(Sort.Order.desc("createTime")))); String userId = user.userId();
String key = KeyConstant.ITEM_LIKE;
Page<TbCfItemComment> allByItemId = commentRepository.findAllByItemId(itemId, PageRequest.of(pageNum, pageSize, Sort.by(Sort.Order.desc("createTime"))));
List<TbCfItemComment> comments = allByItemId.toList(); List<TbCfItemComment> comments = allByItemId.toList();
if (limit != null)
if (comments.size() > 0 && comments != null) {
if (limit != null) {
comments.stream().limit(limit); comments.stream().limit(limit);
}
comments.forEach(c -> {
String liked = (String) redisCache.get(key + userId + "_" + c.getId());
c.setLike(liked == null ? false : true);
Integer count = (Integer) redisCache.get(key + c.getId());
c.setLikeCount(count == null ? 0 : count);
});
}
result.setData(comments); result.setData(comments);
// } catch (Exception e) { } catch (Exception e) {
// result.setCode(ResultCodeEnum.SERVICE_ERROR.getCode()); result.setCode(ResultCodeEnum.SERVICE_ERROR.getCode());
// result.setMessage(ResultCodeEnum.SERVICE_ERROR.getDesc()); result.setMessage(ResultCodeEnum.SERVICE_ERROR.getDesc());
// } }
return result;
}
@GetMapping("/getItemLike/{commentId}")
public Result getItemLike(@PathVariable("commentId") String commentId) {
Result result = new Result();
try {
String userId = user.userId();
if (StringUtils.isBlank(commentId)) {
result.setCode(ResultCodeEnum.VALIDATE_ERROR.getCode());
result.setMessage("The commentId parameter cannot be empty");
}
if (StringUtils.isBlank(userId)) {
result.setCode(ResultCodeEnum.UN_LOGIN.getCode());
result.setMessage(ResultCodeEnum.UN_LOGIN.getDesc());
}
String likeItemKey = KeyConstant.ITEM_LIKE + commentId;
String userKey = KeyConstant.ITEM_LIKE + userId + "_" + commentId;
Long likeNum = 0L;
if (redisCache.setNx(userKey, likeItemKey)) {
likeNum = redisCache.incr(likeItemKey);
} else {
redisCache.delete(userKey);
likeNum = redisCache.decr(likeItemKey);
}
return result.setData(likeNum);
} catch (Exception e) {
result.setCode(ResultCodeEnum.SERVICE_ERROR.getCode());
result.setMessage(ResultCodeEnum.SERVICE_ERROR.getDesc());
}
return result; return result;
} }
} }
...@@ -13,8 +13,8 @@ public enum ResultCodeEnum { ...@@ -13,8 +13,8 @@ public enum ResultCodeEnum {
DAO_ERROR(9004, "dao error"), DAO_ERROR(9004, "dao error"),
NEED_LOGIN(10, "need login"), NEED_LOGIN(10, "need login"),
SYSTEM_ERROR(100, "Other system anomalies"), SYSTEM_ERROR(100, "Other system anomalies"),
ILLEGAL_ARGUMENT(2, "illegal argument"); ILLEGAL_ARGUMENT(2, "illegal argument"),
UN_LOGIN(401, "need login");
//成员变量(常量) //成员变量(常量)
private final int code; private final int code;
......
...@@ -11,6 +11,7 @@ import javax.annotation.Nullable; ...@@ -11,6 +11,7 @@ import javax.annotation.Nullable;
import javax.persistence.*; import javax.persistence.*;
import java.io.Serializable; import java.io.Serializable;
import java.util.Date; import java.util.Date;
import java.util.List;
/** /**
* 实体 * 实体
...@@ -21,7 +22,7 @@ import java.util.Date; ...@@ -21,7 +22,7 @@ import java.util.Date;
*/ */
@Entity @Entity
@Data @Data
public class TbCfItemComment{ public class TbCfItemComment {
/** /**
* 商品评论ID * 商品评论ID
...@@ -33,8 +34,8 @@ public class TbCfItemComment{ ...@@ -33,8 +34,8 @@ public class TbCfItemComment{
*/ */
@ManyToOne @ManyToOne
@JsonIgnore @JsonIgnore
@JoinColumn(columnDefinition = "user_id",name = "user_id") @JoinColumn(columnDefinition = "user_id", name = "user_id")
@NotFound(action= NotFoundAction.IGNORE) @NotFound(action = NotFoundAction.IGNORE)
private TbCfUserInfo user; private TbCfUserInfo user;
/** /**
* 订单ID * 订单ID
...@@ -51,6 +52,7 @@ public class TbCfItemComment{ ...@@ -51,6 +52,7 @@ public class TbCfItemComment{
/** /**
* 图片或视频的url * 图片或视频的url
*/ */
@JsonIgnore
private String urls; private String urls;
/** /**
* 商品评分 * 商品评分
...@@ -85,7 +87,7 @@ public class TbCfItemComment{ ...@@ -85,7 +87,7 @@ public class TbCfItemComment{
*/ */
private Date createTime; private Date createTime;
// @Transient // @Transient
private Integer real; private Integer real;
/** /**
* 更新时间 * 更新时间
...@@ -104,9 +106,19 @@ public class TbCfItemComment{ ...@@ -104,9 +106,19 @@ public class TbCfItemComment{
@Transient @Transient
private boolean isLike; private boolean isLike;
@Formula(value = "(SELECT IFNULL(COUNT(*),0) FROM tb_cf_item_like lk where lk.comment_id = id)") // @Formula(value = "(SELECT IFNULL(COUNT(*),0) FROM tb_cf_item_like lk where lk.comment_id = id)")
private int likeCount; private int likeCount;
private double score;
public double getScore() {
return (double) (itemScore + serviceScore + logisticsScore + priceScore) / 4;
}
public void setScore(double score) {
this.score = score;
}
public boolean isLike() { public boolean isLike() {
return isLike; return isLike;
} }
...@@ -138,6 +150,7 @@ public class TbCfItemComment{ ...@@ -138,6 +150,7 @@ public class TbCfItemComment{
// public void setItemName(String itemName) { // public void setItemName(String itemName) {
// this.itemName = itemName; // this.itemName = itemName;
// } // }
/** /**
* 设置:商品评论ID * 设置:商品评论ID
*/ */
...@@ -161,7 +174,7 @@ public class TbCfItemComment{ ...@@ -161,7 +174,7 @@ public class TbCfItemComment{
@PostLoad @PostLoad
public void catchName(){ public void catchName() {
this.userName = user == null ? "" : user.display(); this.userName = user == null ? "" : user.display();
this.avatar = user == null ? "" : user.getAvatar(); this.avatar = user == null ? "" : user.getAvatar();
} }
...@@ -230,6 +243,10 @@ public class TbCfItemComment{ ...@@ -230,6 +243,10 @@ public class TbCfItemComment{
return urls; return urls;
} }
public String[] getImgs() {
return urls != null ? urls.split(";") : null;
}
/** /**
* 设置:商品评分 * 设置:商品评分
*/ */
......
...@@ -23,7 +23,7 @@ import java.util.List; ...@@ -23,7 +23,7 @@ import java.util.List;
@Entity @Entity
@Getter @Getter
@Setter @Setter
@Where(clause="enable_flag=1") @Where(clause = "enable_flag=1")
public class TbCfStationItem { public class TbCfStationItem {
...@@ -127,11 +127,11 @@ public class TbCfStationItem { ...@@ -127,11 +127,11 @@ public class TbCfStationItem {
@JsonIgnore @JsonIgnore
@ManyToOne @ManyToOne
@JoinColumn(columnDefinition = "template",name = "template") @JoinColumn(columnDefinition = "template", name = "template")
private TbCfExpressTemplate express; private TbCfExpressTemplate express;
@Formula(value = "(SELECT IFNULL(CEILING(SUM((a.item_score+a.service_score+a.logistics_score+a.price_score)/4)/COUNT(a.item_id)),5) FROM tb_cf_item_comment a WHERE a.item_id=item_id)") @Formula(value = "(SELECT IFNULL(ROUND(SUM((a.item_score+a.service_score+a.logistics_score+a.price_score)/4)/COUNT(a.item_id),1),5.0) FROM tb_cf_item_comment a WHERE a.item_id=item_id)")
private int totalScore = 0; private double totalScore;
@JsonIgnore @JsonIgnore
...@@ -180,11 +180,11 @@ public class TbCfStationItem { ...@@ -180,11 +180,11 @@ public class TbCfStationItem {
return itemCode; return itemCode;
} }
public int getTotalScore() { public double getTotalScore() {
return totalScore; return totalScore;
} }
public BigDecimal getOneOfPrices(){ public BigDecimal getOneOfPrices() {
return discountPrice == null ? itemPrice == null ? BigDecimal.ZERO : itemPrice : discountPrice; return discountPrice == null ? itemPrice == null ? BigDecimal.ZERO : itemPrice : discountPrice;
} }
...@@ -288,11 +288,12 @@ public class TbCfStationItem { ...@@ -288,11 +288,12 @@ public class TbCfStationItem {
} }
//Get first image from many separated by comma //Get first image from many separated by comma
public String catchSingleImage(){ public String catchSingleImage() {
String itemImg = getItemImg(); String itemImg = getItemImg();
String[] strings = itemImg != null ? itemImg.split(";") : new String[]{}; String[] strings = itemImg != null ? itemImg.split(";") : new String[]{};
return strings.length > 0 ? strings[0] : itemImg; return strings.length > 0 ? strings[0] : itemImg;
} }
/** /**
* 设置:搜索关键字 * 设置:搜索关键字
*/ */
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论