当前位置:网站首页>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);
}
});
}
边栏推荐
- Make a ThreadLocal (source code) that everyone can understand
- Bidding announcement: Oracle database maintenance service procurement of the First Affiliated Hospital of Jinan University
- What is the difference between the FAT32 and NTFS formats on the USB flash disk
- AXI总线
- 巧用redis实现点赞功能,它不比mysql香吗?
- Integration of entry-level SSM framework based on XML configuration file
- 【微服务|Sentinel】热点规则|授权规则|集群流控|机器列表
- 重读经典:《The Craft of Research(1)》
- MySQL index and its classification
- R language objects are stored in JSON
猜你喜欢

What if the win system cannot complete the update and is revoking the status change

巧用redis实现点赞功能,它不比mysql香吗?

SFINAE

High efficiency exponentiation

Buuctf Misc

Crane: a new way of dealing with dictionary items and associated data
![[microservices sentinel] hotspot rules | authorization rules | cluster flow control | machine list](/img/42/efebf981888704b3ad42d7d4404aa7.png)
[microservices sentinel] hotspot rules | authorization rules | cluster flow control | machine list
Principle Comparison and analysis of mechanical hard disk and SSD solid state disk

Acwing game 57

enable_if
随机推荐
EventLoop learning
Completely solve the problem of Chinese garbled code in Web Engineering at one time
Interviewer: do you understand redis' shared object pool?
Practice of constructing ten billion relationship knowledge map based on Nebula graph
同花顺能开户炒股吗?安全吗?
A method to realize automatic renaming of pictures uploaded by WordPress
Daily question 3 (2): check binary string field
做一篇人人能搞懂的ThreadLocal(源码)
打印输出数(递归方法解决)
Brief reading of dynamic networks and conditional computing papers and code collection
力扣 第 81 场双周赛
Calcul de la confidentialité Fate - Prévisions hors ligne
SFINAE
Julia1.1 installation instructions
Awk concise tutorial
Axi bus
JVM parameter setting and analysis
[WUSTCTF2020]girlfriend
Rereading the classic: the craft of research (1)
Deep understanding of bit operations