pip3 install flask
pip3 install redis==3.5.3
pip3 install celery==5.0.0
1、安装gcc
yum install -y gcc
2、下载并解压
wget http://download.redis.io/releases/redis-5.0.3.tar.gz
tar -zxvf redis-5.0.3.tar.gz
3、切换到解压目录下,编译
cd redis-5.0.3
make
make MALLOC=libc
4、安装并安装指定目录
make install PREFIX=/usr/local/redis
5、设置后台启动服务
cp /usr/local/redis-5.0.3/redis.conf /usr/local/redis/bin/
vi /usr/local/redis/bin/redis.conf
修改 redis.conf 文件,把 daemonize no 改为 daemonize yes
启动测试:
./redis-server redis.conf
6、设置开机自启动(设置成服务)
vi /etc/systemd/system/redis.service
复制如下内容
[Unit]
Description=redis-server
After=network.target
[Service]
Type=forking
ExecStart=/usr/local/redis/bin/redis-server /usr/local/redis/bin/redis.conf
PrivateTmp=true
[Install]
WantedBy=multi-user.target
设置开机启动
[root@localhost bin]# systemctl daemon-reload
[root@localhost bin]# systemctl start redis.service
[root@localhost bin]# systemctl enable redis.service
7、设置软连接
ln -s /usr/local/redis/bin/redis-cli /usr/bin/redis
本文测试为了简单,暂不设置redis密码
以下是设置redis密码以及将redis密码还原的过程,特此记录一下
1、进入redis
redis
2、查看密码
config get requirepass
config set requirepass 123456
再使用config get requirepass,显示需要认证
4、修改为无密码
1、认证
auth 123456
2、设置为无密码
config set requirepass ""
1、切换数据库
select 1
2、查询
keys *
3、根据键值查询
get 键名
项目目录如下:
api–接口文件夹
task–celery相关任务文件夹
app.py–项目启动文件
settings.py–项目配置文件
import os
class Config(object):
BASEDIR = os.path.abspath(os.path.dirname(__file__))
DEBUG = True
TESTING = False
class ProjectConfig(Config):
CELERY_BROKER_URL = "redis://localhost:6379/0"
CELERY_RESULT_BACKEND = "redis://localhost:6379/1"
from flask import Flask
from api.create_task import task
app = Flask(__name__)
app.config.from_object('settings.ProjectConfig')
app.register_blueprint(task,url_prefix='/req')
if __name__ == '__main__':
app.run()
# task:任务
# broker(中间人):存储任务的队列
# worker:真正执行任务的工作者
# backend:用来存储任务执行后的结果
from celery import Celery
import time
celery = Celery("tasks",
broker="redis://localhost:6379/0",
backend="redis://localhost:6379/1")
@celery.task #加上此装饰器,这个函数就变成celery任务了(task)
def send_mail():
print('邮件开始发送....')
time.sleep(10)
print('邮件发送结束!')
from flask import Blueprint
from task.tasks import send_email
task = Blueprint('task',__name__)
@task.route('/add_task',methods=['GET'])
def add_task():
"""
添加任务
:return:
"""
send_email.delay()
return '添加成功 !!!'
1、启动任务监听
切换到项目目录下
celery -A celery_task.tasks worker --loglevel=INFO
注意:如果报错:bash: celery: 未找到命令…
执行以下命令
export PATH=/usr/local/python3/bin:$PATH # /usr/local/python3为python3编译文件夹
echo 'export PATH=/usr/local/python3/bin:$PATH' >> /etc/profile.d/python3.sh # 避免重启丢失