feat (infra): Trae 完成 asset_helper_backend 微服务基础架构 V1 初始化
核心实现:搭建 Monorepo 架构,完成 shared 共享包、gateway、user-service 基础框架开发 技术落地:严格匹配指定技术栈版本,完成 Docker、gRPC、FastAPI、PostgreSQL、Redis 等配置,实现服务间基础连通 配套文件:生成 Makefile、环境变量模板、数据库 / 脚本初始化文件及启动验证文档 架构定位:仅搭建基础架构骨架,无任何业务逻辑、业务规则及业务相关字段,为后续业务开发提供支撑
This commit is contained in:
22
asset_helper_backend/services/gateway/app/ws/handlers.py
Normal file
22
asset_helper_backend/services/gateway/app/ws/handlers.py
Normal file
@@ -0,0 +1,22 @@
|
||||
from fastapi import WebSocket, WebSocketDisconnect
|
||||
from app.ws.manager import manager
|
||||
import uuid
|
||||
|
||||
async def websocket_handler(websocket: WebSocket):
|
||||
client_id = str(uuid.uuid4())
|
||||
await manager.connect(websocket, client_id)
|
||||
|
||||
try:
|
||||
while True:
|
||||
data = await websocket.receive()
|
||||
|
||||
if "text" in data:
|
||||
message = data["text"]
|
||||
await manager.send_personal_message(f"You said: {message}", client_id)
|
||||
await manager.broadcast(f"Client {client_id} said: {message}")
|
||||
elif "bytes" in data:
|
||||
# 处理二进制消息
|
||||
await websocket.send_bytes(data["bytes"])
|
||||
except WebSocketDisconnect:
|
||||
manager.disconnect(client_id)
|
||||
await manager.broadcast(f"Client {client_id} disconnected")
|
||||
24
asset_helper_backend/services/gateway/app/ws/manager.py
Normal file
24
asset_helper_backend/services/gateway/app/ws/manager.py
Normal file
@@ -0,0 +1,24 @@
|
||||
from fastapi import WebSocket
|
||||
from typing import Dict, List
|
||||
|
||||
class ConnectionManager:
|
||||
def __init__(self):
|
||||
self.active_connections: Dict[str, WebSocket] = {}
|
||||
|
||||
async def connect(self, websocket: WebSocket, client_id: str):
|
||||
await websocket.accept()
|
||||
self.active_connections[client_id] = websocket
|
||||
|
||||
def disconnect(self, client_id: str):
|
||||
if client_id in self.active_connections:
|
||||
del self.active_connections[client_id]
|
||||
|
||||
async def send_personal_message(self, message: str, client_id: str):
|
||||
if client_id in self.active_connections:
|
||||
await self.active_connections[client_id].send_text(message)
|
||||
|
||||
async def broadcast(self, message: str):
|
||||
for connection in self.active_connections.values():
|
||||
await connection.send_text(message)
|
||||
|
||||
manager = ConnectionManager()
|
||||
Reference in New Issue
Block a user