当前位置: 首页 > news >正文

自己做的网站涉黄谷歌搜索引擎 google

自己做的网站涉黄,谷歌搜索引擎 google,dedecms做企业网站,重庆市招标网官网最近要实现一个在线聊天功能,基于fastapi的websocket实现了这个功能。下面介绍一下遇到的技术问题 1.问题难点 在线上环境部署时,一般是多进程的方式进行部署启动fastapi服务,而每个启动的进程都有自己的独立存储空间。导致存储的连接对象分…

最近要实现一个在线聊天功能,基于fastapi的websocket实现了这个功能。下面介绍一下遇到的技术问题

1.问题难点

在线上环境部署时,一般是多进程的方式进行部署启动fastapi服务,而每个启动的进程都有自己的独立存储空间。导致存储的连接对象分布在不同的进程中,当进行通信时,可能无法找到已连接的连接对象。

2.解决方案

使用使用redis的订阅发布机制,使所有的进程都能进行消息订阅。这样能保证每个进程收到消息后都会进行相关的信息处理了。

3.方案设计

  • 每个进程启动的时候都进行一个消息的订阅。
  • 通过http请求,进行消息发布。
  • 每个进程收到发布的消息后,进行判断是否由自己进行处理。

4.代码实现

①在服务启动时,进行消息订阅,并一直监听消息通道。当有消息发布时,进行消息处理。

# 初始化app
app = FastAPI(title="Ws Chat", description="测试", version="1.0.0")
app.openapi_version = "3.0.0"app.include_router(chat.app, prefix='/api/chat', tags=['Chat'])@app.on_event('startup')
async def on_startup():print(f"订阅初始化:{os.getpid()}")# 执行消息订阅机制https://aioredis.readthedocs.io/en/latest/examples/loop = asyncio.get_event_loop()loop.create_task(register_pubsub())async def reader(channel):# 进行消息的消费async for msg in channel.listen():  # 监听通道# print(msg)msg_data = msg.get("data")if msg_data and isinstance(msg_data, str):msg_data_dict = json.loads(msg_data)print(f"chat:{msg_data_dict}")sender = msg_data_dict.get("sender")# 进行消息处理await chat.cm.handle_websocket_message(msg_data_dict, sender)async def register_pubsub():pool = aioredis.from_url("redis://{}".format(host), db=db, password=password, port=port, encoding="utf-8", decode_responses=True)psub = pool.pubsub()async with psub as p:# 消息订阅await p.subscribe("chat")await reader(p)await p.unsubscribe("chat")

②websocket处理类

from fastapi import WebSocket, WebSocketDisconnectclass ConnectionManager:def __init__(self):# 保存当前所有的链接的websocket对象self.websocket_connections = {}async def connect(self, websocket: WebSocket, client_id):# 添加连接并发送欢迎消息await websocket.accept()self.websocket_connections[client_id] = websocketawait websocket.send_json({"type": "system","msg": "Welcome to the chat app!","sender": "system","recipient": client_id})try:# 处理消息while True:# 获取信息message = await websocket.receive_json()# 处理发送信息await self.handle_websocket_message(message, client_id)except WebSocketDisconnect:# 连接断开时移除连接del self.websocket_connections[client_id]async def handle_websocket_message(self, message: dict, client_id):# 处理私聊消息if message.get("type") == "private_message":recipient = message.get("recipient")msg = message.get("msg")recipient_conn = self.websocket_connections.get(recipient)if recipient_conn:# 在线await recipient_conn.send_json({"type": "private_message","sender": client_id,"msg": msg,"recipient": recipient})async def broadcast(self, message: dict):# 循环变量给所有在线激活的链接发送消息-全局广播for connection in self.websocket_connections:await connection.send_text(message)async def close(self, websocket: WebSocket, client_id):# 断开客户端的链接await websocket.close()del self.websocket_connections[client_id]async def disconnect(self, user_id):websocket: WebSocket = self.websocket_connections[user_id]await websocket.close()del self.websocket_connections[user_id]

③websocket连接

from app.chat_manager.server import ConnectionManagercm = ConnectionManager()@app.websocket("/connect_chat")
async def connect_chat(websocket: WebSocket, user_code: str):try:await cm.connect(websocket, user_code)except WebSocketDisconnect:# 连接断开时移除连接del cm.websocket_connections[user_code]

④http请求进行消息发布

@app.post("/create_chat", summary="发起聊天")
async def create_chat(param: DiagnosisChatSch, r=Depends(get_redis)):""""""ws_param = {"type": "private_message","msg": param.msg,"sender": param.sender,"recipient": param.recipient}# 进行消息发布await r.publish('diagnosis_chat', json.dumps(ws_param))return {'code': 200, 'msg': '成功', 'data': ''}

5.源码

github源码地址:https://github.com/zhangyukuo/fastapi_ws_chat

6.参考文章

https://www.cnblogs.com/a00ium/p/16931133.html

http://www.tj-hxxt.cn/news/95814.html

相关文章:

  • 聊城网站建设费用在线seo工具
  • 烟台网站排名系统互联网平台推广怎么做
  • 个人网站链接怎么做品牌策划公司哪家好
  • 云南网站建设专业品牌建网络平台要多少费用
  • wordpress文章自动标签重庆seo网站管理
  • canvas做的手机网站seo兼职平台
  • 综合信息网站模板情感营销经典案例
  • 手机新闻网站模板美国婚恋网站排名
  • 购买网站服务器域名查询 站长查询
  • 邵阳汽车网站建设seo网站关键词优化方法
  • 个人怎么找猎头公司推荐自己微博搜索引擎优化
  • 哪里有做网站公司的seo外包优化公司
  • 游戏网站开发运营的几个思路营销的概念是什么
  • 企业网站设计特点seo诊断报告
  • 福田网站建设团队成都网络营销推广公司
  • 怎样建网站赚钱网站alexa排名
  • 凡科建站登录入口官方正版南京网络推广优化哪家好
  • 济南做网站哪里好网络营销图片
  • 网站后期增加内容开发做一个网站需要多少钱
  • 香港服务器网站可以做淘宝客吗八种营销模式
  • 一级a做爰片免费观看网站百度点击工具
  • 上海知名网站建西安网站建设制作
  • 福田招聘信息昆明网络推广优化
  • 如何看网站是不是织梦做的seo搜索引擎优化师
  • 上海集团网站建设价格东莞营销网站建设优化
  • 主流电商网站开发框架seo整站优化报价
  • 西安做网站的公司客服电商平台营销策划方案
  • 个人可做网站需要什么材料网站开发平台有哪些
  • 自媒体自助下单网站怎么做信息互联网推广
  • 青岛做网站皆赴青岛博网站收录提交