当前位置:网站首页>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
边栏推荐
- 【EXSI】主机间传输文件
- Restcloud ETL WebService data synchronization to local
- Mouse over effect I
- Record a service deployment failure troubleshooting
- Restcloud ETL data realizes incremental data synchronization through timestamp
- [QT] add knowledge supplement of third-party database
- How the network is connected: Chapter 2 (Part 2) packet receiving and sending operations between IP and Ethernet
- [linear DP] longest common subsequence
- PTA 1017
- Mnasnet learning notes
猜你喜欢
![Od modify DLL and exe pop-up contents [OllyDbg]](/img/ff/7249e6e6644376ae048b23bf63b046.jpg)
Od modify DLL and exe pop-up contents [OllyDbg]

Prototype and prototype chain in JS

Redis高效点赞与取消功能

最新接口自动化面试题

HTB-Lame

STM32 - DS18B20 temperature sampling of first-line protocol

基于Pytorch完整的训练一个神经网络并进行验证

【小程序项目开发-- 京东商城】uni-app之分类导航区域

Introduction to kubernetes resource objects and common commands (II)

Saving images of different depths in opencv
随机推荐
Huawei operator level router configuration example | configuration optionA mode cross domain LDP VPLS example
Saving images of different depths in opencv
UE4 rendering pipeline learning notes
Codeforces Round #416 (Div. 2) C. Vladik and Memorable Trip
【机器学习】向量化计算 -- 机器学习路上必经路
IEDA 右键源码文件菜单简介
JS to find duplicate elements in two arrays
Completely solve the lost connection to MySQL server at 'reading initial communication packet
Share Creators萌芽人才培养计划来了!
鼠标悬停效果八
kubernetes资源对象介绍及常用命令(二)
股票开户安全吗?上海股票开户步骤。
[PR # 5 A] two way running (state pressure DP)
使用ipmitool配置X86服务器的BMC网络和用户信息
robots.txt限制搜索引擎收录
鼠标悬停效果四
【小程序项目开发 -- 京东商城】uni-app 商品分类页面(下)
Densenet network paper learning notes
Const and the secret of pointers
[linear DP] longest common subsequence