当前位置:网站首页>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
边栏推荐
- HTB-Lame
- POI导出excel,按照父子节点进行分级显示
- 最好用的信任关系自动化脚本(shell)
- js中的原型和原型链
- 基于OPENCV和图像减法的PCB缺陷检测
- Borrowing constructor inheritance and composite inheritance
- 鼠标悬停效果二
- 实战 ELK 优雅管理服务器日志
- [applet project development -- Jingdong Mall] user defined search component of uni app (Part 1)
- Complete training and verification of a neural network based on pytorch
猜你喜欢
![[applet project development -- Jingdong Mall] user defined search component of uni app (Part 1)](/img/73/a22ab1dbb46e743ffd5f78b40e66a2.png)
[applet project development -- Jingdong Mall] user defined search component of uni app (Part 1)

So easy 将程序部署到服务器

Xception learning notes

限流组件设计实战

Voici le programme de formation des talents de SHARE Creators!

STM32 - DS18B20 temperature sampling of first-line protocol

xxl-job使用指南
![[machine learning] vectorized computing -- a must on the way of machine learning](/img/3f/d672bb254f845ea705b3a0ca10ee19.png)
[machine learning] vectorized computing -- a must on the way of machine learning

VMware vSphere 6.7虚拟化云管理之12、VCSA6.7更新vCenter Server许可

Example of Huawei operator level router configuration | example of configuring optionc mode cross domain LDP VPLS
随机推荐
Mouse over effect 8
最新接口自动化面试题
Is it safe to open an account online in a small securities firm? Will my money be unsafe?
mybati sql 语句打印
Huawei operator level router configuration example | configuration optionA mode cross domain LDP VPLS example
Mouse over effect III
Magnetic manometer and measurement of foreign coins
Mysql知识点
MySQL index --01--- design principle of index
PCB defect detection based on OpenCV and image subtraction
Servlet [first introduction]
鼠标悬停效果七
If a parent class defines a parameterless constructor, is it necessary to call super ()?
lavaweb【初识后续问题的解决】
Metadata in NFT
Lavaweb [first understanding the solution of subsequent problems]
robots. Txt restrict search engine inclusion
基于OPENCV和图像减法的PCB缺陷检测
在国内如何买港股的股?用什么平台安全一些?
JS to find duplicate elements in two arrays