当前位置:网站首页>Using redis skillfully to realize the like function, isn't it more fragrant than MySQL?
Using redis skillfully to realize the like function, isn't it more fragrant than MySQL?
2022-06-27 14:06:00 【InfoQ】
MAP_USER_LIKED Be liked by users id:: Like user id1 perhaps 0MAP_USER_LIKED_COUNT Be liked by users idcount/**
* Save the data that users like by other users to redis
*/
@Override
public void saveLiked2Redis(String likedUserId, String likedPostId) {
String key = RedisKeyUtils.getLikedKey(likedUserId, likedPostId);
redisTemplate.opsForHash().put(RedisKeyUtils.MAP_KEY_USER_LIKED,key, LikedStatusEnum.LIKE.getCode());
}
// Cancel likes
@Override
public void unlikeFromRedis(String likedUserId, String likedPostId) {
String key = RedisKeyUtils.getLikedKey(likedUserId, likedPostId);
redisTemplate.opsForHash().put(RedisKeyUtils.MAP_KEY_USER_LIKED,key,LikedStatusEnum.UNLIKE.getCode());
}
/**
* Number of users who will be liked +1
*/
@Override
public void incrementLikedCount(String likedUserId) {
redisTemplate.opsForHash().increment(RedisKeyUtils.MAP_KEY_USER_LIKED_COUNT,likedUserId,1);
}
//-1
@Override
public void decrementLikedCount(String likedUserId) {
redisTemplate.opsForHash().increment(RedisKeyUtils.MAP_KEY_USER_LIKED_COUNT, likedUserId, -1);
}
/**
* obtain Redis User likes details record in
*/
@Override
public List<UserLikeDetail> getLikedDataFromRedis() {
Cursor<Map.Entry<Object,Object>> scan = redisTemplate.opsForHash().scan(RedisKeyUtils.MAP_KEY_USER_LIKED, ScanOptions.NONE);
List<UserLikeDetail> list = new ArrayList<>();
while (scan.hasNext()){
Map.Entry<Object, Object> entry = scan.next();
String key = (String) entry.getKey();
String[] split = key.split("::");
String likedUserId = split[0];
String likedPostId = split[1];
Integer value = (Integer) entry.getValue();
// Assemble into UserLike object
UserLikeDetail userLikeDetail = new UserLikeDetail(likedUserId, likedPostId, value);
list.add(userLikeDetail);
// Deposit in list From Redis Delete in
redisTemplate.opsForHash().delete(RedisKeyUtils.MAP_KEY_USER_LIKED, key);
}
return list;
}
/**
* obtain Redis The number of users like in
*/
@Override
public List<UserLikCountDTO> getLikedCountFromRedis() {
Cursor<Map.Entry<Object,Object>> cursor = redisTemplate.opsForHash().scan(RedisKeyUtils.MAP_KEY_USER_LIKED_COUNT, ScanOptions.NONE);
List<UserLikCountDTO> list = new ArrayList<>();
while(cursor.hasNext()){
Map.Entry<Object, Object> map = cursor.next();
String key = (String) map.getKey();
Integer value = (Integer) map.getValue();
UserLikCountDTO userLikCountDTO = new UserLikCountDTO(key,value);
list.add(userLikCountDTO);
// Deposit in list From Redis Delete in
redisTemplate.opsForHash().delete(RedisKeyUtils.MAP_KEY_USER_LIKED_COUNT,key);
}
return list;
}


DROP TABLE IF EXISTS `user_like_detail`;
CREATE TABLE `user_like_detail` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`liked_user_id` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT ' Liked users id',
`liked_post_id` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT ' Thumb up users id',
`status` tinyint(1) NULL DEFAULT 1 COMMENT ' Like status ,0 Cancel ,1 give the thumbs-up ',
`create_time` timestamp(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT ' Creation time ',
`update_time` timestamp(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) ON UPDATE CURRENT_TIMESTAMP(0) COMMENT ' Modification time ',
PRIMARY KEY (`id`) USING BTREE,
INDEX `liked_user_id`(`liked_user_id`) USING BTREE,
INDEX `liked_post_id`(`liked_post_id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 7 CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = ' The user likes the watch ' ROW_FORMAT = Dynamic;
SET FOREIGN_KEY_CHECKS = 1;
DROP TABLE IF EXISTS `user_like_count`;
CREATE TABLE `user_like_count` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`like_num` int(11) NULL DEFAULT 0,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 7 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
SET FOREIGN_KEY_CHECKS = 1;
// Sync redis The user likes the data to the database
@Override
@Transactional
public void transLikedFromRedis2DB() {
List<UserLikeDetail> list = redisService.getLikedDataFromRedis();
list.stream().forEach(item->{
// Duplicate check
UserLikeDetail userLikeDetail = userLikeDetailMapper.selectOne(new LambdaQueryWrapper<UserLikeDetail>()
.eq(UserLikeDetail::getLikedUserId, item.getLikedUserId())
.eq(UserLikeDetail::getLikedPostId, item.getLikedPostId()));
if (userLikeDetail == null){
userLikeDetail = new UserLikeDetail();
BeanUtils.copyProperties(item, userLikeDetail);
// There is no record , Deposit directly into
userLikeDetail.setCreateTime(LocalDateTime.now());
userLikeDetailMapper.insert(userLikeDetail);
}else{
// Records , You need to update
userLikeDetail.setStatus(item.getStatus());
userLikeDetail.setUpdateTime(LocalDateTime.now());
userLikeDetailMapper.updateById(item);
}
});
}
@Override
@Transactional
public void transLikedCountFromRedis2DB() {
List<UserLikCountDTO> list = redisService.getLikedCountFromRedis();
list.stream().forEach(item->{
UserLikeCount user = userLikeCountMapper.selectById(item.getKey());
// The number of likes is irrelevant , You don't need to throw exceptions if you make mistakes
if (user != null){
Integer likeNum = user.getLikeNum() + item.getValue();
user.setLikeNum(likeNum);
// Update likes
userLikeCountMapper.updateById(user);
}
});
}
边栏推荐
- 高效率取幂运算
- MySQL index and its classification
- Axi bus
- 剑指 Offer II 039. 直方图最大矩形面积 单调栈
- 线程同步之信号量
- [a complete human-computer interface program framework]
- A brief analysis of the differences between domestic and foreign e-commerce
- Sword finger offer II 039 Histogram maximum rectangular area monotonic stack
- Openssf security plan: SBOM will drive software supply chain security
- R language objects are stored in JSON
猜你喜欢

全球芯片市场或陷入停滞,中国芯片逆势扩张加速提升自给率

类模板中可变参的逐步展开

enable_ if

【微服务|Sentinel】热点规则|授权规则|集群流控|机器列表

关于接口测试自动化的总结与思考
![[advanced MySQL] MTS master-slave synchronization principle and Practice Guide (7)](/img/d6/1b916f49ad02dee4ab2c26add324df.png)
[advanced MySQL] MTS master-slave synchronization principle and Practice Guide (7)

芯片供给过剩之际,进口最多的中国继续减少进口,美国芯片慌了
![[安洵杯 2019]Attack](/img/1a/3e82a54cfcb90ebafebeaa8ee1ec01.png)
[安洵杯 2019]Attack
Principle Comparison and analysis of mechanical hard disk and SSD solid state disk

How to set the compatibility mode of 360 speed browser
随机推荐
【业务安全-01】业务安全概述及测试流程
Awk concise tutorial
[XMAN2018排位赛]通行证
ENSP cloud configuration
AXI总线
buuctf misc 百里挑一
Implementing springboard agent through SSH port forwarding configuration
Privacy computing fat offline prediction
SFINAE
CMOS level circuit analysis
海量数据!秒级分析!Flink+Doris构建实时数仓方案
[WUSTCTF2020]girlfriend
enable_if
[business security-04] universal user name and universal password experiment
[daily 3 questions (3)] maximum number of balls in the box
Pytorch learning 1 (learning documents on the official website)
How to solve the problem of missing language bar in win10 system
Learning records of numpy Library
[an Xun cup 2019]attack
隐私计算FATE-离线预测