抖音项目消息模块 | 青训营笔记

118 阅读2分钟

这是我参与「第五届青训营 」伴学笔记创作活动的第 12 天

需求分析

消息:客户端通过定时轮询服务端接口查询消息记录

/douyin/message/chat/- 聊天记录

当前登录用户和其他指定用户的聊天消息记录

接口类型

GET

接口定义

syntax = "proto3";  
package message;  
option go_package = "message";  
  
message BaseResp {
  int32 status_code = 1;//状态码
  string status_message = 2;//状态描述
  int64 service_time = 3;//服务时间
}

message Message {
  int64 id = 1; // 消息id  
  int64 to_user_id = 2; // 该消息接收者的id  
  int64 from_user_id =3; // 该消息发送者的id  
  string content = 4; // 消息内容  
  int64 create_time = 5; // 消息创建时间  
}  
  
message message_chat_request {  
  string token = 1; // 用户鉴权token  
  int64 to_user_id = 2; // 对方用户id  
  int64 pre_msg_time = 3; // 上次最新消息的时间  
}  
  
message message_chat_response {  
  BaseResp base_resp = 1;  
  repeated Message message_list = 2; // 消息列  
} 

/douyin/message/action/- 消息操作

登录用户对消息的相关操作,目前只支持消息发送

接口类型

POST

接口定义

message message_action_request {  
  string token = 1; // 用户鉴权 token  
  int64 to_user_id = 2; // 对方用户 id  
  int32 action_type = 3; // 1- 发送消息  
  string content = 4; // 消息内容  
}  
  
message message_action_response {  
  BaseResp base_resp = 1;  
}

RPC 服务接口设计:

service MessageService {  
  rpc MessageAction (message_action_request) returns (message_action_response) {}  
  rpc MessageChat (message_chat_request) returns (message_chat_response) {}  
}

数据表定义

// MessageRaw Gorm Data Structurestype 
MessageRaw struct {  
   gorm.Model  
   UserId     int64  `gorm:"column:user_id;not null;index:idx_userid"`  
   ToUserId   int64  `gorm:"column:to_user_id;not null;index:idx_touserid"`  
   Content    string `gorm:"column:content;not null;index:idx_content"`  
   CreateTime int64  `gorm:"column:create_time;not null;index:idx_createtime;autoCreateTime"` // 使用时间戳秒数填充创建时间  
}

业务处理逻辑

  1. 聊天记录
  • 判断发送的请求的字段是否正确(非 0,非空等);
  • 对用户进行 JWT 认证,如果没有登陆,返回登陆提示信息;若已经登陆,查看是否存在该用户;
  • 在 relation 数据表里查询互相关注的用户 ID,根据好友 ID 和自己 ID 在 message 数据表里查询最新的消息记录,返回响应;
  1. 消息发送
  • 判断发送的请求的字段是否正确(非 0,非空等);
  • 对用户进行 JWT 认证,如果没有登陆,返回登陆提示信息;若已经登陆,查看是否存在该用户;
  • 在 message 数据表里查询聊天记录,返回相应的响应信息。

详细实现代码可参考 项目地址