当前位置:网站首页>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 !
边栏推荐
- Raki's notes on reading paper: neighborhood matching network for entity alignment
- 学术汇报(academic presentation)/PPT应该怎么做?
- Global and Chinese market of mobile commerce solutions 2022-2028: Research Report on technology, participants, trends, market size and share
- Playful palette: an interactive parametric color mixer for artists
- What is a self signed certificate? Advantages and disadvantages of self signed SSL certificates?
- 并发请求下如何防重复提交
- 【postgres】postgres 数据库迁移
- CA数字证书包含哪些文件?如何查看SSL证书信息?
- What is certificate transparency CT? How to query CT logs certificate logs?
- Cmake tutorial series-01-minimum configuration example
猜你喜欢

Shenzhen CPDA Data Analyst Certification in July 2022

Jupyter notebook displays a collection of K-line graphs

Precautions for purchasing wildcard SSL certificate

Digicert、Sectigo、Globalsign代码签名证书的区别

Differences among digicert, SECTIONO and globalsign code signing certificates

Pytorch学习(二)

CMake教程系列-02-使用cmake代码生成二进制

Série de tutoriels cmake - 02 - génération de binaires à l'aide du Code cmake

oracle怎么设置密码复杂度及超时退出的功能

SSL证书七大常见错误及解决方法
随机推荐
怎么使用Vant实现数据分页和下拉加载
Playful palette: an interactive parametric color mixer for artists
Two methods of SSL certificate format conversion
2022年7月深圳地区CPDA数据分析师认证
什么是证书透明度CT?如何查询CT logs证书日志?
JMeter obtains cookies across thread groups or JMeter thread groups share cookies
2022 the action of protecting the net is imminent. Things about protecting the net
五个最便宜的通配符SSL证书品牌
Linear algebra Chapter 3 summary of vector and vector space knowledge points (Jeff's self perception)
Wechat applet page Jump and parameter transfer
Cmake tutorial series -05- options and variables
Merge sort
Redis+AOP怎么自定义注解实现限流
三层交换机和二层交换机区别是什么
Time complexity analysis
多卡服务器使用
IBM WebSphere channel connectivity setup and testing
Mysql表数据比较大情况下怎么修改添加字段
IBM websphere通道联通搭建和测试
Global and Chinese market of wind energy equipment logistics 2022-2028: Research Report on technology, participants, trends, market size and share