当前位置:网站首页>Mobile asynchronous sending SMS verification code solution -efficiency+redis
Mobile asynchronous sending SMS verification code solution -efficiency+redis
2022-07-04 00:40:00 【Mr_ WoLong】
Celery Introduction and use
One .Celery Introduce :
- A simple 、 Flexible and reliable 、 A distributed system that processes a large number of messages , Can run on one or more machines . Celery Is a fully functional plug and play task queue
- Single Celery Processes can handle millions of tasks per minute . Communicating through messages , Using message queuing (broker) Coordinate between clients and consumers .
install Celery:
$ pip install -U Celery
Celery Official documents :https://docs.celeryq.dev/en/latest/index.html
1. Producer consumer design pattern
One of the most commonly used decoupling methods , Find a middleman (broker) Bridging , Ensure that the two businesses are not directly related .
We call this decoupling method : Producer consumer design pattern 
summary :
- Producers generate messages , Cache to message queue , The consumer reads the message in the message queue and executes .
- Send SMS messages generated by Mido mall , Cache to message queue , The consumer reads the SMS message sent in the message queue and executes the message .
2. A middleman broker
Example : Here's a demo of Redis The database acts as an intermediary broker
Celery We need a way to send and receive messages , We call this intermediate device used to store messages message broker, It can also be called a message broker .
As a middleman , We have several options :
1.RabbitMQ
- RabbitMQ Is a fully functional , Stable and easy to install broker. It is the best choice in the production environment .
Use RabbitMQ For details, please refer to the following links :http://docs.celeryproject.org/en/latest/getting-started/brokers/rabbitmq.html#broker-rabbitmq
If you are using Ubuntu perhaps Debian Distribution Linux, You can install directly through the command RabbitMQ:
sudo apt-get install rabbitmq-server
After installation ,RabbitMQ-server The server is already running in the background .
If not Ubuntu or Debian, You can visit the following website :
http://www.rabbitmq.com/download.html
Find the version of software you need .
2.Redis
Redis It is also a fully functional broker optional , But it is more likely to cause data loss due to accidental interruption or power failure .
About that Redis As Broker, Visit the following website : http://docs.celeryproject.org/en/latest/getting-started/brokers/redis.html#broker-redis
3.celery Framework pseudocode
# queue , A middleman
class Broker(object):
# Task queue
broker_list = []
# consumer
class Worker(object):
# Task executor
def run(self, broker, func):
if func in broker.broker_list:
func()
else:
return 'error'
# Celery Will this 3 person It's connected in series
class Celery(object):
def __init__(self):
self.broker = Broker()
self.worker = Worker()
def add(self, func):
self.broker.broker_list.append(func)
def work(self, func):
self.worker.run(self.broker,func)
# Mission ( function ), producer
def send_sms_code():
print('send_sms_code')
# 1. establish celery example
app=Celery()
# 2. Add tasks
app.add(send_sms_code)
# 3. Perform tasks
app.work(send_sms_code)
2. Use
1) establish Celery Instance and load the configuration
1. Definition Celery package 
2. establish Celery example 
mian File code celery_tasks.main.py
# 0. by celery Operation of Set up Django Environment
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'meiduo_mall.settings')
# 1. establish celery example
from celery import Celery
# Parameters 1: main Just set the script path . The script path is unique
app=Celery('celery_tasks')
#2. Set up broker
# We set by loading the configuration file broker
app.config_from_object('celery_tasks.config')
#3. need celery Automatically detect the task of the specified package
# autodiscover_tasks The parameter is the list
# The elements in the list are tasks The path of
app.autodiscover_tasks(['celery_tasks.sms','celery_tasks.email'])
3. load Celery To configure 
Code config.py
broker_url = "redis://127.0.0.1/15"
########################### explain #############################
# If you use someone else as an intermediary , For example, using rabbitmq
# be rabbitmq The configuration is as follows :
# broker_url= 'amqp:// user name : password @ip Address :5672'
# for example :
# meihao: stay rabbitq User name created in , Be careful : Cannot use... When remote link guest Account .
# 123456: stay rabbitq The password corresponding to the user name in
# ip part : It means the present rabbitq The computer where you are ip
# 5672: Is the specified port number
# broker_url = 'amqp://meihao:[email protected]:5672'
2) Define the task of sending SMS

1. Registration task :celery_tasks.main.py
# Automatic registration celery Mission
#3. need celery Automatically detect the task of the specified package
# autodiscover_tasks The parameter is the list
# The elements in the list are tasks The path of
app.autodiscover_tasks(['celery_tasks.sms','celery_tasks.email'])
2. Define the task :celery_tasks.sms.tasks.pytask.py Code
# producer -- Mission , function
# 1. This function Must let celery Instance task Decorator decorate
# 2. need celery Automatically detect the task of the specified package
from libs.yuntongxun.sms import CCP
from celery_tasks.main import app
@app.task
def celery_send_sms_code(mobie,code):
CCP().send_template_sms(mobie,[code,5],1)
Example demo
from celery_tasks.main import celery_app
from libs.yuntongxun.sms import CCP
import logging
logger = logging.getLogger('django')
# name: Asynchronous task alias
@celery_app.task(name='send_sms_code')
def send_sms_code(mobile, sms_code):
""" Send SMS asynchronous task :param mobile: cell-phone number :param sms_code: SMS verification code """
try:
send_ret = CCP().send_template_sms(mobile, [sms_code, 5], 1)
except Exception as e:
logger.error(e)
4) start-up Celery service
Enter the virtual environment , Enter the command :$ celery -A celery_tasks.main worker -l INFO
- -A Refers to the corresponding application , Its parameters are in the project Celery The location of the instance .
- worker It refers to the... To be started here worker.
- -l Refers to the log level , such as info Grade .

5) Call send SMS task
Send SMS business logic code
from celery_tasks.sms.tasks import celery_send_sms_code
# delay Parameters of Equate to Mission ( function ) Parameters of
celery_send_sms_code.delay(mobile,sms_code)
Example demo
# Send SMS verification code
# CCP().send_template_sms(mobile,[sms_code, 5], 1)
# Celery Send SMS verification code asynchronously
send_sms_code.delay(mobile, sms_code)
6) Add celery worker Working mode of
- The default is process pool mode , The number of processes on the current machine CPU For reference , Every CPU Open four processes .
- How to specify the number of processes : celery worker -A proj --concurrency=4
- How to change the process pool mode to co process mode : celery worker -A proj --concurrency=1000 -P eventlet
-c 1000
install eventlet modular : $ pip install eventlet
Enable Eventlet pool : $ celery -A celery_tasks.main worker -l info -P eventlet -c 1000
边栏推荐
- Unity elementary case notes of angry birds Siki college 1-6
- Development and application of fcitx functional plug-ins
- Analysis: misunderstanding of choosing WMS warehouse management system
- Recommendation of knowledge base management system
- Global and Chinese markets for instant saliva testing devices 2022-2028: Research Report on technology, participants, trends, market size and share
- Network layer - routing
- Reading notes on how programs run
- AI Challenger 2018 text mining competition related solutions and code summary
- 打印菱形图案
- MySQL 8.0.12 error: error 2013 (HY000): lost connection to MySQL server during query
猜你喜欢

Celebrate the new year | Suihua fire rescue detachment has wonderful cultural activities during the Spring Festival

1-Redis架构设计到使用场景-四种部署运行模式(上)

NLP pre training technology development

Struct in linked list

Yyds dry goods inventory three JS source code interpretation - getobjectbyproperty method

A-Frame虚拟现实开发入门

The FISCO bcos console calls the contract and reports an error does not exist
![[NLP] text classification still stays at Bert? Duality is too strong than learning framework](/img/49/1ff6025bdb0445e5638c1451e0b267.jpg)
[NLP] text classification still stays at Bert? Duality is too strong than learning framework

Bodong medical sprint Hong Kong stocks: a 9-month loss of 200million Hillhouse and Philips are shareholders

Network layer - routing
随机推荐
P1629 postman delivering letter
Optimization of for loop
Private project practice sharing populate joint query in mongoose makes the template unable to render - solve the error message: syntaxerror: unexpected token r in JSON at
P1339 [USACO09OCT]Heat Wave G
Pytest unit test framework: simple and easy to use parameterization and multiple operation modes
NLP pre training technology development
Pair
Unity elementary case notes of angry birds Siki college 1-6
1214 print diamond
P3371 [template] single source shortest path (weakened version)
swagger中响应参数为Boolean或是integer如何设置响应描述信息
Why use get/set instead of exposing properties
STM32 key light
基于.NetCore开发博客项目 StarBlog - (14) 实现主题切换功能
On covariance of array and wildcard of generic type
Global and Chinese market of underwater bags 2022-2028: Research Report on technology, participants, trends, market size and share
Weekly open source project recommendation plan
What is the future of software testing industry? Listen to the test veterans' answers
AI Challenger 2018 text mining competition related solutions and code summary
PMP 考试常见工具与技术点总结