1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286
| from fastapi import APIRouter, WebSocket, WebSocketDisconnect, Depends from typing import List, Dict import json import asyncio from datetime import datetime
router = APIRouter()
class ConnectionManager: """WebSocket连接管理器""" def __init__(self): self.active_connections: List[WebSocket] = [] self.user_connections: Dict[str, WebSocket] = {} async def connect(self, websocket: WebSocket, user_id: str = None): await websocket.accept() self.active_connections.append(websocket) if user_id: self.user_connections[user_id] = websocket def disconnect(self, websocket: WebSocket, user_id: str = None): self.active_connections.remove(websocket) if user_id and user_id in self.user_connections: del self.user_connections[user_id] async def send_personal_message(self, message: str, websocket: WebSocket): await websocket.send_text(message) async def send_to_user(self, message: str, user_id: str): if user_id in self.user_connections: websocket = self.user_connections[user_id] await websocket.send_text(message) async def broadcast(self, message: str): for connection in self.active_connections: try: await connection.send_text(message) except: self.active_connections.remove(connection)
manager = ConnectionManager()
@router.websocket("/ws/{client_id}") async def websocket_endpoint(websocket: WebSocket, client_id: str): await manager.connect(websocket, client_id) try: while True: data = await websocket.receive_text() message_data = json.loads(data) if message_data["type"] == "chat": chat_message = { "type": "chat", "user_id": client_id, "message": message_data["message"], "timestamp": datetime.now().isoformat() } await manager.broadcast(json.dumps(chat_message)) elif message_data["type"] == "private": target_user = message_data["target_user"] private_message = { "type": "private", "from_user": client_id, "message": message_data["message"], "timestamp": datetime.now().isoformat() } await manager.send_to_user(json.dumps(private_message), target_user) elif message_data["type"] == "ping": pong_message = { "type": "pong", "timestamp": datetime.now().isoformat() } await manager.send_personal_message(json.dumps(pong_message), websocket) except WebSocketDisconnect: manager.disconnect(websocket, client_id) disconnect_message = { "type": "user_disconnect", "user_id": client_id, "timestamp": datetime.now().isoformat() } await manager.broadcast(json.dumps(disconnect_message))
class ChatRoom: def __init__(self, room_id: str): self.room_id = room_id self.connections: Dict[str, WebSocket] = {} self.messages: List[Dict] = [] async def add_user(self, user_id: str, websocket: WebSocket): await websocket.accept() self.connections[user_id] = websocket for message in self.messages[-50:]: await websocket.send_text(json.dumps(message)) join_message = { "type": "user_join", "user_id": user_id, "timestamp": datetime.now().isoformat() } await self.broadcast(json.dumps(join_message), exclude_user=user_id) def remove_user(self, user_id: str): if user_id in self.connections: del self.connections[user_id] async def broadcast(self, message: str, exclude_user: str = None): for user_id, websocket in self.connections.items(): if user_id != exclude_user: try: await websocket.send_text(message) except: pass async def add_message(self, user_id: str, message: str): message_data = { "type": "message", "user_id": user_id, "message": message, "timestamp": datetime.now().isoformat() } self.messages.append(message_data) await self.broadcast(json.dumps(message_data))
chat_rooms: Dict[str, ChatRoom] = {}
@router.websocket("/chat/{room_id}/{user_id}") async def chat_websocket(websocket: WebSocket, room_id: str, user_id: str): if room_id not in chat_rooms: chat_rooms[room_id] = ChatRoom(room_id) room = chat_rooms[room_id] await room.add_user(user_id, websocket) try: while True: data = await websocket.receive_text() message_data = json.loads(data) if message_data["type"] == "message": await room.add_message(user_id, message_data["content"]) except WebSocketDisconnect: room.remove_user(user_id) leave_message = { "type": "user_leave", "user_id": user_id, "timestamp": datetime.now().isoformat() } await room.broadcast(json.dumps(leave_message))
@router.websocket("/notifications/{user_id}") async def notification_websocket(websocket: WebSocket, user_id: str): await manager.connect(websocket, user_id) try: while True: await asyncio.sleep(30) ping_message = { "type": "ping", "timestamp": datetime.now().isoformat() } await websocket.send_text(json.dumps(ping_message)) except WebSocketDisconnect: manager.disconnect(websocket, user_id)
@router.post("/send-notification") async def send_notification(user_id: str, message: str, notification_type: str = "info"): notification = { "type": "notification", "notification_type": notification_type, "message": message, "timestamp": datetime.now().isoformat() } await manager.send_to_user(json.dumps(notification), user_id) return {"message": "通知发送成功"}
```python
import redis.asyncio as redis import json from typing import Optional, Any from datetime import timedelta import pickle
class RedisCache: def __init__(self, redis_url: str = "redis://localhost:6379"): self.redis = redis.from_url(redis_url, decode_responses=False) async def get(self, key: str) -> Optional[Any]: """获取缓存值""" try: value = await self.redis.get(key) if value: return pickle.loads(value) return None except Exception as e: print(f"缓存获取失败: {e}") return None async def set(self, key: str, value: Any, expire: int = 3600) -> bool: """设置缓存值""" try: serialized_value = pickle.dumps(value) await self.redis.set(key, serialized_value, ex=expire) return True except Exception as e: print(f"缓存设置失败: {e}") return False async def delete(self, key: str) -> bool: """删除缓存""" try: await self.redis.delete(key) return True except Exception as e: print(f"缓存删除失败: {e}") return False async def exists(self, key: str) -> bool: """检查键是否存在""" return await self.redis.exists(key) async def expire(self, key: str, seconds: int) -> bool: """设置过期时间""" return await self.redis.expire(key, seconds) async def clear_pattern(self, pattern: str) -> int: """清除匹配模式的键""" keys = await self.redis.keys(pattern) if keys: return await self.redis.delete(*keys) return 0
cache = RedisCache()
from functools import wraps import hashlib
def cache_result(expire: int = 3600, key_prefix: str = ""): """缓存函数结果的装饰器""" def decorator(func): @wraps(func) async def wrapper(*args, **kwargs): cache_key = f"{key_prefix}:{func.__name__}:" key_data = str(args) + str(sorted(kwargs.items())) cache_key += hashlib.md5(key_data.encode()).hexdigest() cached_result = await cache.get(cache_key) if cached_result is not None: return cached_result result = await func(*args, **kwargs) await cache.set(cache_key, result, expire) return result return wrapper return decorator
|