基于Redis的购物车、订单的实现代码
时间: 2024-03-12 09:47:57 浏览: 111
以下是基于Redis的购物车和订单实现代码示例:
购物车:
```python
import redis
class ShoppingCart:
def __init__(self, user_id):
self.redis_client = redis.StrictRedis(host='localhost', port=6379, db=0)
self.user_id = user_id
self.cart_key = f"cart:{user_id}"
def add_item(self, product_id, quantity):
self.redis_client.hincrby(self.cart_key, product_id, quantity)
def remove_item(self, product_id):
self.redis_client.hdel(self.cart_key, product_id)
def get_items(self):
items = self.redis_client.hgetall(self.cart_key)
return {product_id.decode(): int(quantity.decode()) for product_id, quantity in items.items()}
def clear(self):
self.redis_client.delete(self.cart_key)
```
订单:
```python
import redis
class Order:
def __init__(self, user_id):
self.redis_client = redis.StrictRedis(host='localhost', port=6379, db=0)
self.user_id = user_id
self.order_key = f"order:{user_id}"
def place_order(self, items):
pipeline = self.redis_client.pipeline()
pipeline.delete(self.order_key)
for product_id, quantity in items.items():
pipeline.hincrby(self.order_key, product_id, quantity)
pipeline.execute()
def get_order(self):
items = self.redis_client.hgetall(self.order_key)
return {product_id.decode(): int(quantity.decode()) for product_id, quantity in items.items()}
def cancel_order(self):
self.redis_client.delete(self.order_key)
```
这里假设每个用户都有一个唯一的 `user_id`,购物车和订单的数据都存储在 Redis 数据库中,使用 hash 类型来存储商品和数量的键值对,购物车的键为 `cart:{user_id}`,订单的键为 `order:{user_id}`。购物车和订单都有添加商品、删除商品、清空购物车/取消订单和获取购物车/订单的方法。在下单时,将购物车中的商品复制到订单中并清空购物车。
阅读全文