当前位置:网站首页>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
边栏推荐
- Evaluation of the entry-level models of 5 mainstream smart speakers: apple, Xiaomi, Huawei, tmall, Xiaodu, who is better?
- Prototype and prototype chain in JS
- Introduction and basic knowledge of machine learning
- Restcloud ETL WebService data synchronization to local
- 鼠标悬停效果六
- Complete training and verification of a neural network based on pytorch
- 实战 ELK 优雅管理服务器日志
- Youmeng (a good helper for real-time monitoring of software exceptions: crash) access tutorial (the easiest tutorial for Xiaobai with some foundation)
- [applet project development -- Jingdong Mall] user defined search component of uni app (Part 1)
- Nacos configuration center tutorial
猜你喜欢

Example of Huawei operator level router configuration | example of configuring optionc mode cross domain LDP VPLS

Restcloud ETL practice data row column conversion

Const and the secret of pointers

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

【小程序项目开发-- 京东商城】uni-app之首页商品楼层

第03章_用户与权限管理

Mnasnet learning notes
![[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)

DenseNet网络论文学习笔记

Redis高效点赞与取消功能
随机推荐
kubernetes资源对象介绍及常用命令(二)
调试定位导航遇到的问题总结
So easy 将程序部署到服务器
php批量excel转word
Redis高效点赞与取消功能
Mouse over effect VI
Codeforces Round #416 (Div. 2) C. Vladik and Memorable Trip
[exsi] transfer files between hosts
Lavaweb [first understanding the solution of subsequent problems]
How the network is connected: Chapter 2 (Part 2) packet receiving and sending operations between IP and Ethernet
Use ipmitool to configure BMC network and user information of X86 server
[applet project development -- Jingdong Mall] classified navigation area of uni app
Restcloud ETL practice to realize incremental data synchronization without identification bit
Voici le programme de formation des talents de SHARE Creators!
【机器学习】向量化计算 -- 机器学习路上必经路
实战 ELK 优雅管理服务器日志
Mouse over effect 9
Restcloud ETL WebService data synchronization to local
Xception learning notes
Detailed explanation of pointer array and array pointer (comprehensive knowledge points)