当前位置:网站首页>10. Redis implements likes (Set) and obtains the total number of likes
10. Redis implements likes (Set) and obtains the total number of likes
2022-07-31 02:40:00 【A snicker】
实现点赞
No need to write the data access layer,直接在Servicelayer can be written.
1、创建RedisKeyUtil工具类生成key:
public class RedisKeyUtil {
private static final String SPLIT = ":";
private static final String PREFIX_ENTITY_LIKE = "like:entity";
// 某个实体的赞
// like:entity:entityType:entityId -> set(userId)
public static String getEntityLikeKey(int entityType, int entityId) {
return PREFIX_ENTITY_LIKE + SPLIT + entityType + SPLIT + entityId;
}
}
2、LikeService
@Service
public class LikeService {
@Autowired
private RedisTemplate redisTemplate;
// 点赞,查看该用户userId是否在集合里,Not in the set,加进去,like;在集合里,取消点赞,remove掉
public void like(int userId, int entityType, int entityId) {
String entityLikeKey = RedisKeyUtil.getEntityLikeKey(entityType, entityId);
boolean isMember = redisTemplate.opsForSet().isMember(entityLikeKey, userId);
if (isMember) {
redisTemplate.opsForSet().remove(entityLikeKey, userId);// 取消点赞
} else {
redisTemplate.opsForSet().add(entityLikeKey, userId);
}
}
// 查询某实体点赞的数量,See how many are in the setuserId
public long findEntityLikeCount(int entityType, int entityId) {
String entityLikeKey = RedisKeyUtil.getEntityLikeKey(entityType, entityId);
return redisTemplate.opsForSet().size(entityLikeKey);
}
// 查询某人对某实体的点赞状态,看某userId是否在集合里,返回1点赞了,返回0没点赞(Tap to go back-1)
public int findEntityLikeStatus(int userId, int entityType, int entityId) {
String entityLikeKey = RedisKeyUtil.getEntityLikeKey(entityType, entityId);
return redisTemplate.opsForSet().isMember(entityLikeKey, userId) ? 1 : 0;
}
}
3、LikeController
@Controller
public class LikeController {
@Autowired
private LikeService likeService;
@Autowired
private HostHolder hostHolder;
@RequestMapping(path = "/like", method = RequestMethod.POST)
@ResponseBody
public String like(int entityType, int entityId) {
User user = hostHolder.getUser();
// 点赞
likeService.like(user.getId(), entityType, entityId);
// 重新计算数量
long likeCount = likeService.findEntityLikeCount(entityType, entityId);
// 重新计算状态
int likeStatus = likeService.findEntityLikeStatus(user.getId(), entityType, entityId);
Map<String, Object> map = new HashMap<>();
map.put("likeCount", likeCount);
map.put("likeStatus", likeStatus);
return CommunityUtil.getJSONString(0, null, map);
}
}
4、异步请求,discuss.js
function like(btn, entityType, entityId) {
$.post(
CONTEXT_PATH + "/like",
{
"entityType":entityType,"entityId":entityId},
function(data) {
data = $.parseJSON(data);
if(data.code == 0) {
$(btn).children("i").text(data.likeCount);
$(btn).children("b").text(data.likeStatus==1?'已赞':"赞");
} else {
alert(data.msg);
}
}
);
}
Get total likes
1、改key拼接工具类RedisKeyUtil
private static final String PREFIX_USER_LIKE = "like:user";
// The total number of likes for a user, value是Object->强转成Integer->intValue()转成int型
// like:user:userId -> int
public static String getUserLikeKey(int userId){
return PREFIX_USER_LIKE + SPLIT + userId;
}
2、LikeService,编程式事务
保证事务性,Add two likes at once,编程式事务
public void like(int userId, int entityType, int entityId, int entityUserId) {
// 保证事务性,Two likes at a time increase,编程式事务
redisTemplate.execute(new SessionCallback() {
@Override
public Object execute(RedisOperations operations) throws DataAccessException {
String entityLikeKey = RedisKeyUtil.getEntityLikeKey(entityType, entityId);
String userLikeKey = RedisKeyUtil.getUserLikeKey(entityUserId);
// The query should precede the transaction,It cannot be placed in a transaction,Otherwise, the transaction will be executed after committing.
boolean isMember = operations.opsForSet().isMember(entityLikeKey, userId);
operations.multi();
if (isMember) {
operations.opsForSet().remove(entityLikeKey, userId);// 取消点赞
operations.opsForValue().decrement(userLikeKey);// Decrease the number of likes for an entity
}else{
operations.opsForSet().add(entityLikeKey, userId);// 点赞
operations.opsForValue().increment(userLikeKey);// Increase the number of likes for an entity
}
return operations.exec();
}
});
}
Query the total number of likes a user has received
// Query the total number of likes a user has received
public int findUserLikeCount(int userId) {
String userLikeKey = RedisKeyUtil.getUserLikeKey(userId);
Integer count = (Integer) redisTemplate.opsForValue().get(userLikeKey);
return count == null ? 0 : count.intValue();
}
边栏推荐
- Introduction and use of Drools WorkBench
- Coldfusion file read holes (CVE - 2010-2861)
- 【shell基础】判断目录是否为空
- Intranet Infiltration - Privilege Escalation
- Validate XML documents
- 关于 mysql8.0数据库中主键位id,使用replace插入id为0时,实际id插入后自增导致数据重复插入 的解决方法
- JS 函数 this上下文 运行时点语法 圆括号 数组 IIFE 定时器 延时器 self.备份上下文 call apply
- 开题报告之论文框架
- What level of software testing does it take to get a 9K job?
- There is a problem with the multiplayer-hlap package and the solution cannot be upgraded
猜你喜欢
The Sad History of Image Processing Technology
The principle of complete replication of virtual machines (cloud computing)
知识蒸馏7:知识蒸馏代码详解
The whole process scheduling, MySQL and Sqoop
你们程序员为什么不靠自己的项目谋生?而必须为其他人打工?
ShardingJDBC usage summary
12 磁盘相关命令
静态路由解析(最长掩码匹配原则+主备路由)
YOLOV5 study notes (3) - detailed explanation of network module
Software testing basic interface testing - getting started with Jmeter, you should pay attention to these things
随机推荐
8、统一处理异常(控制器通知@ControllerAdvice全局配置类、@ExceptionHandler统一处理异常)
19. Support Vector Machines - Intuitive Understanding of Optimization Objectives and Large Spacing
Drools basic introduction, introductory case, basic syntax
【C语言基础】解决C语言error: expected ‘;‘, ‘,‘ or ‘)‘ before ‘&‘ token
The whole process scheduling, MySQL and Sqoop
MPPT太阳能充放电控制器数据采集-通过网关采集电池电压容量电量SOC,wifi传输
[1154] How to convert string to datetime
全流程调度——MySQL与Sqoop
完整复制虚拟机原理(云计算)
221. Largest Square
Drools Rule Properties, Advanced Syntax
关于 mysql8.0数据库中主键位id,使用replace插入id为0时,实际id插入后自增导致数据重复插入 的解决方法
try-catch中含return
10、Redis实现点赞(Set)和获取总点赞数
经典链表OJ强训题——快慢双指针高效解法
【CV项目调试】CUDNN_CONVOLUTION_FWD_SPECIFY_WORKSPACE_LIMIT问题
TCP/IP四层模型
Basic learning about Redis related content
Software accumulation -- Screenshot software ScreenToGif
静态路由解析(最长掩码匹配原则+主备路由)