user.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package service
  2. import (
  3. "time"
  4. "github.com/patrickmn/go-cache"
  5. )
  6. // UserServiceInterface 用户业务接口
  7. type UserServiceInterface interface {
  8. GetUserMode(userId string) string
  9. SetUserMode(userId, mode string)
  10. ClearUserMode(userId string)
  11. GetUserSessionContext(userId string) string
  12. SetUserSessionContext(userId, content string)
  13. ClearUserSessionContext(userId string)
  14. }
  15. var _ UserServiceInterface = (*UserService)(nil)
  16. // UserService 用戶业务
  17. type UserService struct {
  18. // 缓存
  19. cache *cache.Cache
  20. }
  21. // NewUserService 创建新的业务层
  22. func NewUserService() UserServiceInterface {
  23. return &UserService{cache: cache.New(time.Hour*2, time.Hour*5)}
  24. }
  25. // GetUserMode 获取当前对话模式
  26. func (s *UserService) GetUserMode(userId string) string {
  27. sessionContext, ok := s.cache.Get(userId + "_mode")
  28. if !ok {
  29. return ""
  30. }
  31. return sessionContext.(string)
  32. }
  33. // SetUserMode 设置用户对话模式
  34. func (s *UserService) SetUserMode(userId string, mode string) {
  35. s.cache.Set(userId+"_mode", mode, cache.DefaultExpiration)
  36. }
  37. // ClearUserMode 重置用户对话模式
  38. func (s *UserService) ClearUserMode(userId string) {
  39. s.cache.Delete(userId + "_mode")
  40. }
  41. // SetUserSessionContext 设置用户会话上下文文本,question用户提问内容,GTP回复内容
  42. func (s *UserService) SetUserSessionContext(userId string, content string) {
  43. s.cache.Set(userId+"_content", content, cache.DefaultExpiration)
  44. }
  45. // GetUserSessionContext 获取用户会话上下文文本
  46. func (s *UserService) GetUserSessionContext(userId string) string {
  47. sessionContext, ok := s.cache.Get(userId + "_content")
  48. if !ok {
  49. return ""
  50. }
  51. return sessionContext.(string)
  52. }
  53. // ClearUserSessionContext 清空GTP上下文,接收文本中包含 SessionClearToken
  54. func (s *UserService) ClearUserSessionContext(userId string) {
  55. s.cache.Delete(userId + "_content")
  56. }