4.8 KiB
4.8 KiB
UpdateFanProfileSocial 接口实现总结
概述
成功在 userService 中实现了 UpdateFanProfileSocial 内部 RPC 接口,用于支持 socialService 在好友关系变更时更新粉丝档案的好友数量(social 字段)。
实现时间
2026年1月6日
修改的文件
1. Proto 定义
- 文件:
proto/user.proto - 新增内容:
// 更新粉丝档案social字段请求(内部RPC调用,用于好友数量变更) message UpdateFanProfileSocialRequest { int64 user_id = 1; // 用户ID int64 star_id = 2; // 明星ID int32 delta = 3; // 变化量(正数增加,负数减少) } // 更新粉丝档案social字段响应 message UpdateFanProfileSocialResponse { topfans.common.BaseResponse base = 1; int32 new_social = 2; // 更新后的好友数量 } // RPC 方法定义 rpc UpdateFanProfileSocial(UpdateFanProfileSocialRequest) returns (UpdateFanProfileSocialResponse);
2. Repository 层
- 文件:
services/userService/repository/fan_profile_repository.go - 新增方法:
// UpdateSocial 更新好友数量(social字段) // delta: 变化量,正数表示增加,负数表示减少 // 返回: 更新后的好友数量 func (r *fanProfileRepository) UpdateSocial(userID, starID int64, delta int32) (int32, error) - 实现要点:
- 使用事务确保原子性
- 先查询当前 social 值
- 计算新值(确保不小于 0)
- 更新数据库
- 返回新的 social 值
3. Service 层
- 文件:
services/userService/service/user_service.go - 新增方法:
// UpdateFanProfileSocial 更新粉丝档案的好友数量(内部RPC调用) func (s *userService) UpdateFanProfileSocial(req *pb.UpdateFanProfileSocialRequest) (*pb.UpdateFanProfileSocialResponse, error) - 实现要点:
- 参数验证(user_id、star_id)
- 调用 repository 层更新
- 错误处理和日志记录
- 返回更新后的 social 值
4. Provider 层
-
文件:
services/userService/provider/user_provider.go -
新增方法:
// UpdateFanProfileSocial 更新粉丝档案的好友数量(内部RPC调用) func (p *UserProvider) UpdateFanProfileSocial(ctx context.Context, req *pb.UpdateFanProfileSocialRequest) (*pb.UpdateFanProfileSocialResponse, error) -
文件:
services/userService/provider/unified_provider.go -
新增方法:
// UpdateFanProfileSocial 更新粉丝档案的好友数量(内部RPC调用) func (p *UnifiedProvider) UpdateFanProfileSocial(ctx context.Context, req *pb.UpdateFanProfileSocialRequest) (*pb.UpdateFanProfileSocialResponse, error)
5. 错误定义
- 文件:
pkg/errors/errors.go - 新增错误类型:
ErrInvalidUserID = errors.New("invalid user_id") ErrInternalServer = errors.New("internal server error") - 新增方法:
// BuildBaseResponse 构建基础响应(FormatErrorResponse的别名) func BuildBaseResponse(err error) *pb.BaseResponse
6. SocialService 调用实现
- 文件:
services/socialService/service/user_rpc_client.go - 更新方法:
// UpdateFanProfileSocial 更新粉丝档案的social字段(好友数量) func (c *userServiceClient) UpdateFanProfileSocial(ctx context.Context, userID, starID int64, delta int32) error - 实现要点:
- 调用 userService 的 UpdateFanProfileSocial RPC 接口
- 完整的错误处理和日志记录
- 返回更新结果
使用示例
在 socialService 的 FriendService 中,当好友关系变更时调用:
// 添加好友时
err := s.userClient.UpdateFanProfileSocial(ctx, userID, starID, 1) // +1
// 删除好友时
err := s.userClient.UpdateFanProfileSocial(ctx, userID, starID, -1) // -1
技术要点
- 事务处理: Repository 层使用 GORM 事务确保操作的原子性
- 安全性: 确保 social 值不会变为负数(最小值为 0)
- 错误处理: 完整的错误类型判断和友好的错误信息
- 日志记录: 每个层级都有详细的日志记录
- 内部 RPC: 该接口仅供服务间内部调用,不暴露 HTTP 端点
编译验证
✅ userService 编译成功 ✅ socialService 编译成功 ✅ 无 Linter 错误
后续优化建议
- 批量更新: 如果需要批量更新多个用户的 social 值,可以添加批量接口
- 缓存同步: 如果使用了缓存,需要在更新时同步缓存
- 监控告警: 添加监控指标,当 social 值异常时告警
- 幂等性: 考虑为接口添加幂等性支持