当前位置:网站首页>Share a scheme of "redis" to realize "chat round system" that can't be found on the Internet
Share a scheme of "redis" to realize "chat round system" that can't be found on the Internet
2022-07-27 16:54:00 【Luo Lei】
High quality resource sharing
| Learning route guidance ( Click unlock ) | Knowledge orientation | Crowd positioning |
|---|---|---|
| 🧡 Python Actual wechat ordering applet 🧡 | Progressive class | This course is python flask+ Perfect combination of wechat applet , From the deployment of Tencent to the launch of the project , Create a full stack ordering system . |
| Python Quantitative trading practice | beginner | Take you hand in hand to create an easy to expand 、 More secure 、 More efficient quantitative trading system |
Preface
Why can't I find it on the Internet , Because the author of the scheme about the chat round system almost searched Baidu and couldn't find it , Fortunately, in the end, a big gang with good relations in the company provided some ideas , Finally, the author realized it completely .
Share it and you can collect it , In case you encounter such a need one day , It saves a lot of time .
scene
Let's talk about my scene first , Everyone who has read my article knows , I am in the internet medical industry , Our project includes the chat function , Our clients are mainly doctors in hospitals , When a patient looks for a doctor online , There are often situations where people keep asking .
The only thing doctors can do now is to end the consultation by themselves , Or wait for the system to automatically end , This brings up a problem , Whether the system ends or the doctor ends manually , Patients like to complain and make bad comments , So that the doctor dare not finish without authorization , I'm tired of asking, but I can't reply , If you don't reply, you will be complained .
Finally, the need for the round robin chat system came out , Take the initiative to tell the patient that our chat has a round , So you need to be clear , We won't reply when the rounds are full , If the patient insists on complaining , The doctor can also say , This is set by the company that makes this product .
That's it , We're going to put the pot on .
actually , The birth of the chat round system , Basically, they are similar to the demands of this scene , In order to reduce the frequent and endless consultation of users .
Ideas
combination redis It can well realize the chat round system , Of course, it can also be realized directly through the database , But apparently redis Simpler operation and superior performance .
The general idea is as follows :
1)、redis Store two... In key, One is the representation object , Declare as chat-who:consultId,value Identify objects , For example, here are doctors and patients , For doctors D identification , For patients P identification ; the other one key Is the number of rounds , Declare as chat-num:consultId,value Is the current round number . there consultId Is dynamic , This is a consultation id, Can be determined according to their own business ;
2)、 these two items. key We all set the expiration date for 2 God , The specific expiration time should be adapted according to your own business rules ;
3)、 We initialize at a specific location , As long as it is before entering the chat , Like the scene here , Only after the patient successfully initiated the consultation can they start chatting , We will initialize the number of chat rounds in the method after successful initiation as the default value 6 Round , This default value can also be read dynamically in the form of configuration ;
4)、 We make a judgment in the method of sending messages , obtain redis Medium chat-who:consultId, See if it exists , To exist is to proceed , If it doesn't exist, it means the first message is sent , Then create chat-who:consultId This key To redis in ,value For the current sender D perhaps P;
5)、 Undertaking 4, If chat-who There is , We continue The current message sending object and redis Of chat-who Stored object values are compared , If the same , Then skip regardless , If it's not the same , to update chat-who The value of is the current sender . meanwhile , We judge whether the person who sends the message is a doctor, that is D, yes D Then the number of rounds will be updated , perform -1 operation , The purpose of this is to update the doctor as a dimension of the number of rounds , There can only be one dimension , Only in this way can we ensure that the number of rounds is updated most accurately .
Realization
Next , I use pseudocode to write the whole idea .
1、 Definition redis-key
/**
* Chat round constant
*/
public final class ChatRoundConstants {
/**
* Number of chat rounds key Prefix
*/
public static final String CHAT\_NUM = "chat-num:";
/**
* Chat with key Prefix
*/
public static final String CHAT\_WHO = "chat-who:";
/**
* redis-key Expiration time
*/
public static final Long EXPIRE\_TIME = 48 * 3600L;
/**
* Chat with value value , Doctor -D, In patients with -P.
*/
public static final String DOCTOR = "D";
public static final String PATIENT = "P";
}
2、 Number of initial chat rounds
Initialize before chatting , The scenario of our project here is after the patient successfully initiated the consultation , Initialize in this successful method .
/**
* Successfully initiated the consultation
*/
public void consultSuccess() {
// .... Other business logic processing
// Number of initial chat rounds
initChatRoundNum(ConsultDTO consultDTO);
}
/**
* Number of initial chat rounds
* -- Expiration time 48 Hours
* @param consultDTO Consulting information
*/
private void initChatRoundNum(ConsultDTO consultDTO) {
// initial 6 round
int chatNum = 6;
// Get the default number of rounds configured by the system , Here is the pseudo code written according to your own needs .
ParameterDTO parameterDTO = getConfigValue();
if(!ObjectUtils.isEmpty(parameterDTO)) {
chatNum = parameterDTO.getPvalue();
}
// Initialize to redis,key yes chat-num:consultId
redisService.set(ChatRoundConstants.CHAT_NUM + consultDTO.getId(),
chatNum, ChatRoundConstants.EXPIRE_TIME);
}
3、 Update rounds
Here's the core logic , It is mainly divided into two steps : initialization chat-who:consultId, to update chat-num:consultId.
/**
* Send a message
*/
public void sendMsg() {
// .... Other business logic
// Update chat rounds
handleChatRoundNum(consultDTO, consultDetailInfoDTO);
}
/**
* Number of chat rounds processed
* @param consultDTO Consulting information
* @param consultDetailInfoDTO Chat messages
*/
private void handleChatRoundNum(ConsultDTO consultDTO,
ConsultDetailInfoDTO consultDetailInfoDTO) {
// obtain redis Saved doctor patient id key
String chatWhoKey = ChatRoundConstants.CHAT_WHO + consultDTO.getId();
// Get the corresponding ID of the person sending the message
String current = ChatWhoEnum.getCodeById(consultDetailInfoDTO.getSource());
// chat-who:consultId Whether there is
if(redisService.exists(chatWhoKey)) {
String chatWhoValue = (String) redisService.get(chatWhoKey);
// Judge the current sender and chatWho Whether the value of is the same , If different , to update chatWho For the current sender .
if(!Objects.equals(ChatWhoEnum.getIdByCode(chatWhoValue),
consultDetailInfoDTO.getSource())) {
// to update chatWho For the current sender
redisService.setRange(chatWhoKey, current, 0);
// Judge whether the current message sender is D, yes D Then the number of rounds will be updated .
if(Objects.equals(ChatWhoEnum.DOCTOR.getId(),
consultDetailInfoDTO.getSource())) {
// to update chatNum-1
String chatNumKey = ChatRoundConstants.CHAT_NUM + consultDTO.getId();
int chatNumValue = Integer.parseInt(
(String) redisService.get(chatNumKey)
);
if(redisService.exists(chatNumKey) && chatNumValue > 0) {
redisService.decr(chatNumKey);
}
}
}
} else {
// The nonexistence statement is the first message , To create this key.
redisService.set(chatWhoKey, current, ChatRoundConstants.EXPIRE_TIME);
}
}
Enumeration of message sending objects defined
/**
* Enumeration class of chat object source
*/
public enum ChatWhoEnum {
// source :
// 0 Doctor
// 1 In patients with
DOCTOR(0, "D", " Doctor "),
PATIENT(1, "P", " In patients with ");
private final int id;
private final String code;
private final String label;
ChatWhoEnum(final int id, final String code, final String label) {
this.id = id;
this.code = code;
this.label = label;
}
public int getId() {
return id;
}
public String getCode() {
return code;
}
public String getLabel() {
return label;
}
public static String getCodeById(int id) {
for(ChatWhoEnum type: ChatWhoEnum.values()) {
if(type.getId() == id) {
return type.getCode();
}
}
return null;
}
public static Integer getIdByCode(String code) {
for(ChatWhoEnum type: ChatWhoEnum.values()) {
if(code.equalsIgnoreCase(type.getCode())) {
return type.getId();
}
}
return null;
}
}
summary
In fact, it is very simple to write , It's not difficult to think , But it's hard for you to realize this small function suddenly , If you can't figure it out, you will be stuck in it all the time , When you know it clearly, you will be able to understand it in an instant .
This function has been launched , And it runs stably without any problems , Those who are interested can be collected , If you do chat related business one day , Maybe there will be a similar demand .
My original article is pure hand play , If you feel that you have a little help, please click recommend Well ~
I continue to share practical work experience and mainstream technology , You can pay attention if you like ~
__EOF__
[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-nJd3m1Pz-1655572596912)(https://blog.csdn.net/fulongyuanjushi)] Fulongyuan resident - Link to this article :https://blog.csdn.net/fulongyuanjushi/p/16388264.html
- About bloggers : Comments and private messages will be answered as soon as possible . perhaps Direct personal trust I .
- Copyright notice : All articles in this blog except special statement , All adopt BY-NC-SA license agreement . Reprint please indicate the source !
- Solidarity bloggers : If you think the article will help you , You can click the bottom right corner of the article **【[ recommend ](javascript:void(0)】** once .
边栏推荐
- The difference between MVC and MVP and MVVM
- Mazak handwheel maintenance Mazak little giant CNC machine tool handle operator maintenance av-eahs-382-1
- 牛客题目——链表的奇偶重排、输出二叉树的右视图、括号生成、字符流中第一个不重复的字符
- The bill module of freeswitch
- If you don't want to step on those holes in SaaS, you must first understand the "SaaS architecture"
- 随机数公式Random
- The 31st --- the 52nd
- 【论文阅读】A CNN-Transformer Hybrid Approach for CropClassification Using MultitemporalMultisensor Images
- Circular statements and arrays
- Apache
猜你喜欢

Insert pictures in word to maintain high DPI method

MySQL high version report SQL_ mode=only_ full_ group_ By exception

Life game, universe 25 and striver

Implementation of filler creator material editing tool

【论文阅读】Single- and Cross-Modality Near Duplicate Image PairsDetection via Spatial Transformer Compar

【论文阅读】A CNN-Transformer Hybrid Approach for CropClassification Using MultitemporalMultisensor Images
![[paper reading] transformer with transfer CNN for remote sensing imageobject detection](/img/a2/8ee85e81133326afd86648d9594216.png)
[paper reading] transformer with transfer CNN for remote sensing imageobject detection

Opencv (IV) -- image features and target detection

Great Cells & Counting Grids

Is low code the future of development? On low code platform
随机推荐
Log4j.jar and slf4-log4 download link
LNMP environment - deploy WordPress
Configuration and application of gurobi in pycharm
数据采集之:巧用布隆过滤器提取数据摘要
CDQ divide and conquer and whole dichotomy learning notes
Handling of multiple parts with duplicate names and missing parts when importing SOLIDWORK assemblies into Adams
Bean: Model: Entity的区别
OpenCV(四)——图像特征与目标检测
Database notes sorting
UML图介绍
Quadratic programming based on osqp
OpenCV(二)——图像基本处理
json数据解析
【pytorch】|transforms.FiveCrop
Opencv (II) -- basic image processing
[cqoi2012] local minima & Mike and foam
Opencv (I) -- basic knowledge of image
mvc和mvp和mvvm的区别
Interpretation of C basic syntax: summarize some commonly used but easily confused functions (i++ and ++i) in the program (bit field)
jsp-El表达式,JSTL标签