使用 Flask、Redis 和 RabbitMQ 实现订单处理系统

使用 Flask、Redis 和 RabbitMQ 实现订单处理系统

本文简单介绍了如何使用 Flask、Redis 和 RabbitMQ 实现一个订单处理系统,包括订单创建、库存管理以及超时订单处理。

目录

  1. 项目结构
  2. 环境配置
  3. Redis 操作
  4. RabbitMQ 操作
  5. Flask 应用
  6. 运行项目

项目结构

project/
│
├── app.py
├── redis_operater.py
├── rabbitmq_operator.py
└── config.yaml

环境配置

配置文件 config.yaml

redis:
  host: "localhost"
  port: 6379
  db: 0
  max_connections: 10
  password: "yourpassword"

rabbitmq:
  host: "localhost"
  port: 5672
  virtual_host: "/"
  username: "guest"
  password: "guest"
  heartbeat: 600

安装依赖

requirements.txt 文件中列出所需的依赖:

Flask
redis
pika
PyYAML

使用以下命令安装依赖:

pip install -r requirements.txt

Redis 操作

redis_operater.py

import redis
import yaml

with open("config.yaml", "r") as file:
    config = yaml.safe_load(file)

redis_pool = redis.ConnectionPool(
    host=config["redis"]["host"],
    port=config["redis"]["port"],
    db=config["redis"]["db"],
    max_connections=config["redis"]["max_connections"],
    password=config["redis"]["password"],
)
redis_conn = redis.Redis(connection_pool=redis_pool)

def plus_goods(goods_id, storage: int = 100):
    current_count = redis_conn.get("totalgoodCounts:" + goods_id)
    if current_count is None:
        current_count = 0
    else:
        current_count = int(current_count)

    if current_count >= storage:
        return False

    count = redis_conn.incr("totalgoodCounts:" + goods_id)
    print(count)
    return True

def create_order(order_info):
    user_id = order_info["user_id"]
    goods_id = order_info["goods_id"]
    order_id = order_info["order_id"]
    redis_conn.hset("order:" + order_id, goods_id, user_id)
    redis_conn.expire("order:" + order_id, 60 * 15)
    return True

RabbitMQ 操作

rabbitmq_operator.py

import json
import pika
import yaml

with open("config.yaml", "r") as file:
    config = yaml.safe_load(file)

credentials = pika.PlainCredentials(
    username=config["rabbitmq"]["username"], password=config["rabbitmq"]["password"]
)

parameters = pika.ConnectionParameters(
    host=config["rabbitmq"]["host"],
    port=config["rabbitmq"]["port"],
    virtual_host=config["rabbitmq"]["virtual_host"],
    credentials=credentials,
    heartbeat=config["rabbitmq"]["heartbeat"],
)

try:
    rabbitmq_conn = pika.BlockingConnection(parameters)
    print("连接成功")
except pika.exceptions.AMQPConnectionError as e:
    print(f"连接失败: {e}")
    raise

def create_order_queue(order_info):
    order_id = order_info["order_id"]
    user_id = order_info["user_id"]
    goods_id = order_info["goods_id"]
    if user_id is None or goods_id is None or order_id is None:
        return False
    channel = rabbitmq_conn.channel()
    exchange = "order.exchange"
    queue = "order.queue"
    routing_key = "order." + goods_id + "." + order_id + "." + user_id
    channel.exchange_declare(exchange=exchange, exchange_type="topic", durable=True)
    channel.queue_declare(queue=queue, durable=True)
    channel.queue_bind(exchange=exchange, queue=queue, routing_key=routing_key)
    message = json.dumps(order_info)
    channel.basic_publish(exchange=exchange, routing_key=routing_key, body=message)
    return True

Flask 应用

app.py

import uuid
from flask import Flask, request
from rabbitmq_operator import create_dead_queue, create_order_queue
from redis_operater import create_order, plus_goods

app = Flask(__name__)

@app.route("/purchase", methods=["GET"])
def purchase():
    user_id = request.args.get("user_id")
    goods_id = request.args.get("goods_id")
    res = {
        "status": 200,
        "message": "购买成功",
    }
    order_id = str(uuid.uuid1())
    order_info = {
        "order_id": order_id,
        "user_id": user_id,
        "goods_id": goods_id,
    }
    flag = plus_goods(goods_id)
    if flag:
        try:
            create_order(order_info)
            create_order_queue(order_info)
            create_dead_queue(order_info)
            res["order_info"] = order_info
            return res
        except Exception as e:
            res["status"] = 400
            res["message"] = "网络错误"
            print(e)
            return res
    else:
        res["status"] = 201
        res["message"] = "库存不足"
        return res

if __name__ == "__main__":
    app.run()

运行项目

  1. 启动 Redis 和 RabbitMQ 服务。
  2. 运行 Flask 应用:
python app.py
  1. 通过浏览器或 Postman 访问购买接口:
http://localhost:5000/purchase?user_id=1&goods_id=101
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值