当前位置:网站首页>How to use redis to realize the like function
How to use redis to realize the like function
2022-06-30 02:46:00 【Yisu cloud】
How to use Redis Realize the like function
This article mainly introduces “ How to use Redis Realize the like function ”, In daily operation , I believe many people are using Redis There are doubts about the implementation of the like function , Xiao Bian consulted all kinds of materials , Sort out simple and easy-to-use operation methods , I hope to answer ” How to use Redis Realize the like function ” Your doubts help ! Next , Please follow Xiaobian to learn !
MySQL and Redis Advantages and disadvantages
First, let's talk about the advantages and disadvantages of the two methods : We use MySQL and Redis For example .
1、 Write directly to the database :
advantage : This method is easy to implement , Just complete the addition, deletion, modification and query of the database ;
shortcoming : Database reading and writing pressure is high , If you encounter a situation where a lot of popular articles are liked in a short time , Directly operating the database will bring great pressure to the database , Affect efficiency .
2、 Use Redis cache :
advantage : High performance , Fast reading and writing , Ease the pressure of database reading and writing ;
shortcoming : Development is complex , Data security cannot be guaranteed, i.e redis When you hang up, you lose data , At the same time, it is not synchronized in time redis Data in , May be in redis Memory replacement is eliminated . But we don't need to be so precise about the likes data , It's not a problem to lose a little data .
Next, we will introduce the like function in detail from the following three aspects
•Redis Cache design
• Database design
• Enable scheduled task persistence to database
1、Redis Cache design and implementation
Redis The integration of has been introduced in the last article , I won't go into details here . We learned that , We need to record the following types of data when making a compliment : One is the detailed record of a user being liked by other users , One is . Considering the convenience of query and access , I use Hash Structure for storage , The storage structure is as follows :
(1) A detailed record of a user being liked by other users : MAP_USER_LIKED
Key value , Be liked by users id:: Like user id by filed, 1 perhaps 0 by value
(2) Statistics on the number of likes of a user : MAP_USER_LIKED_COUNT
Key value , Be liked by users id by filed, count
by value
Part of the code is as follows
/*** Save the data that users like by other users to redis*/@Overridepublic 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 @Overridepublic 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*/@Overridepublic void incrementLikedCount(String likedUserId) { redisTemplate.opsForHash().increment(RedisKeyUtils.MAP_KEY_USER_LIKED_COUNT,likedUserId,1);}//[email protected] void decrementLikedCount(String likedUserId) { redisTemplate.opsForHash().increment(RedisKeyUtils.MAP_KEY_USER_LIKED_COUNT, likedUserId, -1);}/*** obtain Redis User likes details record in */@Overridepublic 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 */@Overridepublic 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;}
Redis The storage structure is shown in the figure
2、 Database design
Here we can save the likes data to the database directly , Design two tables :
(1) Detailed records of users being liked by other users :user_like_detail
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;
(2) Statistics on the number of users being liked :user_like_count
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;
3、 Enable scheduled task persistence to database
We use Quartz To achieve timing tasks , take Redis Store the data in the database , For demonstration , We can set one or two minutes to store data , This depends on the specific business . In the process of synchronizing data , First of all, we need to Redis The data in is checked in the database , Discard duplicate data , In this way, our data will be more accurate .
Part of the code is as follows
// Sync redis The user likes the data to the database @[email protected] 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); } });}@[email protected] 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); } });}
Here we are , About “ How to use Redis Realize the like function ” That's the end of my study , I hope we can solve your doubts . The combination of theory and practice can better help you learn , Let's try ! If you want to continue to learn more related knowledge , Please continue to pay attention to Yisu cloud website , Xiaobian will continue to strive to bring you more practical articles !
边栏推荐
- 如何在 JupyterLab 中把 ipykernel 切换到不同的 conda 虚拟环境?
- Implementation of Sanzi chess with C language
- Recursion frog jumping steps problem
- Entering Jiangsu writers and poets carmine Jasmine World Book Day
- What about punctuation in the first column of unity text
- SQLite use
- LeetCode 3. 无重复字符的最长子串
- Wechat applet page Jump and parameter transfer
- Precautions for purchasing wildcard SSL certificate
- 2.< tag-动态规划和0-1背包问题>lt.416. 分割等和子集 + lt.1049. 最后一块石头的重量 II
猜你喜欢
Enlightenment from the revocation of Russian digital certificate by mainstream CA: upgrade the SSL certificate of state secret algorithm to help China's network security to be autonomous and controlla
What is the difference between a layer 3 switch and a layer 2 switch
[Postgres] Postgres database migration
Intel-Hex , Motorola S-Record 格式详细解析
CMake教程系列-02-使用cmake代码生成二进制
Insert sort directly
Unity3D UGUI强制刷新Layout(布局)组件
What files does a CA digital certificate contain? How to view SSL certificate information?
Raki's notes on reading paper: discontinuous named entity recognition as maximum clique discovery
PR second training notes
随机推荐
What about punctuation in the first column of unity text
Seven common errors of SSL certificate and their solutions
打造創客教育中精湛技藝
模板参数包和函数参数包
Cmake tutorial series -04- compiling related functions
Playful palette: an interactive parametric color mixer for artists
How vscode debugs into standard library files / third-party package source code
重看《Redis设计与实现》后记录几个要点
Xunwei NXP itop-imx6 development platform
Raki's notes on reading paper: neighborhood matching network for entity alignment
HTA introductory basic tutorial | GUI interface of vbs script HTA concise tutorial, with complete course and interface beautification
2. < tag dynamic programming and 0-1 knapsack problem > lt.416 Split equal sum subset + lt.1049 Weight of the last stone II
Linear algebra Chapter 4 Summary of knowledge points of linear equations (Jeff's self perception)
【干货分享】最新WHQL徽标认证申请流程
matlab代码运行教程(如何运行下载的代码)
Global and Chinese markets of liquid optical waveguides 2022-2028: Research Report on technology, participants, trends, market size and share
VScode如何Debug(调试)进入标准库文件/第三方包源码
[论]【DSTG】Dynamic SpatiotemporalGraph Convolutional Neural Networks for Traffic Data Imputation
Three solutions to forced hibernation of corporate computers
Several key points recorded after reviewing redis design and Implementation