当前位置:网站首页>Redis efficient like and cancel function
Redis efficient like and cancel function
2022-07-01 03:01:00 【Lingxiyun】
Here we are Lingxiyun studio - Practice makes truth View full text content

image CSDN The like function of only records the quantity , The like function of wechat circle of friends displays the picture of people who like it ( obtain userId Query the user information, encapsulate and return )
give the thumbs-up 、 Cancel likes is a high frequency operation , If you read and write database every time , A lot of operations can affect database performance , Even down , So it is very appropriate to use cache processing . This article takes the article like as an example to describe
Data format selection
Redis Yes 5 The data structures are :String( character string )、List( list )、Set( aggregate )、Hash( hash )、Zset( Ordered set ).
Due to the need to record articles and likes , I like it a little bit ( give the thumbs-up 、 Cancel ), Under the analysis of Redis In data format Hash Most suitable .
because Hash All the data in the are in one Key in , adopt Key It is very convenient to take out all the likes data .Key The data inside can also be saved as Key value pair In the form of , convenient Deposit the likes 、 The person and the state of being praised .
article idbyarticleId,Like people idbyuserId,Like statusby1( give the thumbs-up ) and 0( Cancel likes ).article idandLike people idAsHashKey, Two id Intermediate use::separate ,Like statusAsHashValue.

Integrate SpringBoot
rely on
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
Basic configuration
spring:
redis:
database: 0
host: 127.0.0.1
port: 6379
jedis:
pool:
max-active: 8
max-wait: -1ms
max-idle: 8
min-idle: 0
Configuration class
package cn.goitman.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import javax.sql.DataSource;
import java.sql.SQLException;
/** * @author Nicky * @version 1.0 * @className RedisConfig * @blog goitman.cn | blog.csdn.net/minkeyto * @description Redis Configuration class * @date 2022/5/16 14:40 */
@Configuration
public class RedisConfig {
/** * Use everything to template Of redis All operations must be carried out @Transanctional Annotative transaction , Otherwise, the connection will be occupied all the time , Don't shut down */
@Bean
public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory){
RedisTemplate template = new RedisTemplate();
// change redisTemplate How to serialize ,key In string format ,value by json Format
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
// HashKey and HashValue by json Format
template.setHashKeySerializer(new GenericJackson2JsonRedisSerializer());
template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
template.setConnectionFactory(redisConnectionFactory);
// Turn on transaction support
template.setEnableTransactionSupport(true);
return template;
}
/** * Configure transaction manager */
@Bean
public PlatformTransactionManager transactionManager(DataSource dataSource) throws SQLException {
return new DataSourceTransactionManager(dataSource);
}
}
If redisTemplate No serialization , The data seen in the visualization tool is garbled , It may also be empty when getting data , Fuzzy query ( The following describes ) The function can not be used

Redis Interface
package cn.goitman.service.impl;
import cn.goitman.pojo.Article;
import cn.goitman.pojo.Likes;
import cn.goitman.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/** * @author Nicky * @version 1.0 * @className RedisServiceImpl * @blog goitman.cn | blog.csdn.net/minkeyto * @description Redis Interface implementation class * @date 2022/5/13 16:43 */
@Service
@Transactional
public class RedisServiceImpl implements RedisService {
// I like the article KEY
public static final String KEY_ARTICLE_LIKE = "ARTICLE_LIKE";
// Number of article likes KEY
public static final String KEY_ARTICLE_LIKE_COUNT = "ARTICLE_LIKE_COUNT";
@Autowired
RedisTemplate redisTemplate;
/** * Save the amount of praise and article praise */
@Override
public void saveLike(String articleId, String userId) {
String field = getLikeKey(articleId, userId);
redisTemplate.opsForHash().put(KEY_ARTICLE_LIKE, field, 1);
redisTemplate.opsForHash().increment(KEY_ARTICLE_LIKE_COUNT, articleId, 1);
}
/** * Cancel the amount of praise and article praise */
@Override
public void unLike(String articleId, String userId) {
String field = getLikeKey(articleId, userId);
redisTemplate.opsForHash().put(KEY_ARTICLE_LIKE, field, 0);
redisTemplate.opsForHash().increment(KEY_ARTICLE_LIKE_COUNT, articleId, -1);
}
/** * Delete likes data */
@Override
public void deleteLike(List<Likes> list) {
for (Likes like : list) {
String field = getLikeKey(like.getArticleId(), like.getUserId());
redisTemplate.opsForHash().delete(KEY_ARTICLE_LIKE, field);
}
}
/** * Delete the article likes data */
@Override
public void deleteLikeCount(String articleId) {
redisTemplate.opsForHash().delete(KEY_ARTICLE_LIKE_COUNT, articleId);
}
/** * Get all the like data */
@Override
public List<Likes> getAllLikeData() {
List<Likes> list = new ArrayList<>();
Cursor<Map.Entry<Object, Object>> cursor = redisTemplate.opsForHash().scan(KEY_ARTICLE_LIKE, ScanOptions.NONE);
while (cursor.hasNext()) {
Map.Entry<Object, Object> entry = cursor.next();
String keys = entry.getKey().toString();
String[] keyArr = keys.split("::");
Likes like = new Likes(keyArr[0], keyArr[1], (Integer) entry.getValue());
list.add(like);
}
return list;
}
/** * Get the article likes data */
@Override
public List<Article> getArticleLikeCount() {
List<Article> list = new ArrayList<>();
Cursor<Map.Entry<Object, Object>> cursor = redisTemplate.opsForHash().scan(KEY_ARTICLE_LIKE_COUNT, ScanOptions.NONE);
while (cursor.hasNext()) {
Map.Entry<Object, Object> entry = cursor.next();
String articleId = entry.getKey().toString();
Article article = new Article(articleId, (Integer) entry.getValue());
list.add(article);
}
return list;
}
/** * Splicing articles ID And like people ID As key */
private String getLikeKey(String articleId, String userId) {
return new StringBuilder().append(articleId).append("::").append(userId).toString();
}
}
done , It is so simple and efficient , stay Redis Inside , If the same data exists, it will only be modified value, also Redis Default RDB Persistent data .
Of course, you can also add Limit the number of likes per user within a limited time The logic of , prevent Malicious interface brushing , The logic is simple , I won't go over it here
Here we are Lingxiyun studio - Practice makes truth View full text content
边栏推荐
- [applet project development -- JD mall] uni app commodity classification page (Part 2)
- 股票开户安全吗?上海股票开户步骤。
- Record a service deployment failure troubleshooting
- Huawei operator level router configuration example | BGP VPLS and LDP VPLS interworking example
- lavaweb【初识后续问题的解决】
- Redis高效点赞与取消功能
- Lenovo x86 server restart management controller (xclarity controller) or TSM method
- Why are strings immutable in many programming languages? [repeated] - why are strings immutable in many programming languages? [duplicate]
- Introduction to webrtc concept -- an article on understanding source, track, sink and mediastream
- Mouse over effect 10
猜你喜欢

【Qt】添加第三方库的知识补充

In the industrial Internet, "small" programs have "big" effects

js中的原型和原型链

VMware vSphere 6.7 virtualization cloud management 12. Vcsa6.7 update vCenter server license

单片机 MCU 固件打包脚本软件

实战 ELK 优雅管理服务器日志

Introduction and basic knowledge of machine learning

Contrastive learning of Class-agnostic Activation Map for Weakly Supervised Object Localization and

servlet【初识】

【小程序项目开发 -- 京东商城】uni-app 商品分类页面(上)
随机推荐
彻底解决Lost connection to MySQL server at ‘reading initial communication packet
robots. Txt restrict search engine inclusion
Metadata in NFT
UE4 rendering pipeline learning notes
Dell server restart Idrac method
Complete training and verification of a neural network based on pytorch
An article explaining the publisher subscriber model and the observer model
鼠标悬停效果二
Mouse over effect 10
Cloud native annual technology inventory is released! Ride the wind and waves at the right time
Prototype and prototype chain in JS
鼠标悬停效果八
[linear DP] shortest editing distance
Detailed explanation of pointer array and array pointer (comprehensive knowledge points)
How to open a stock account? Also, is it safe to open an account online?
【机器学习】向量化计算 -- 机器学习路上必经路
Catch 222222
JS to find duplicate elements in two arrays
LeetCode_栈_困难_227.基本计算器(不含乘除)
Network address translation (NAT) technology