token.go 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. package services
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "go-policy-service/models"
  7. "go-policy-service/structs"
  8. "go-policy-service/utils"
  9. "log"
  10. "time"
  11. "github.com/go-redis/redis/v8"
  12. )
  13. type TokenManager struct {
  14. rdb *redis.Client
  15. hgConfig *models.HgConfig
  16. httpClient utils.HTTPClient // 自己请求 token
  17. apiUrl string // 自己请求 token 的接口
  18. }
  19. // 修复构造函数参数声明
  20. func NewTokenManager(
  21. rdb *redis.Client,
  22. hgConfig *models.HgConfig,
  23. httpClient utils.HTTPClient, // 明确参数类型
  24. apiUrl string, // 添加类型声明
  25. ) *TokenManager {
  26. return &TokenManager{
  27. rdb: rdb,
  28. hgConfig: hgConfig,
  29. httpClient: httpClient,
  30. apiUrl: apiUrl,
  31. }
  32. }
  33. func (t *TokenManager) GetAccessToken() (string, error) {
  34. tokenKey := fmt.Sprintf("60s-hgapi-%s", t.hgConfig.Account)
  35. ctx := context.Background()
  36. // 尝试从 Redis 获取现有 token
  37. token, err := t.rdb.Get(ctx, tokenKey).Result()
  38. if err == nil {
  39. return token, nil
  40. }
  41. // 重试机制
  42. const maxRetries = 3
  43. for i := 0; i < maxRetries; i++ {
  44. tokenData, err := t.requestToken()
  45. if err == nil {
  46. expireTimestamp := utils.StringToTimestamp(tokenData.ExpireTime, "2006-01-02 15:04:05")
  47. // 提前半小时失效
  48. durationSeconds := expireTimestamp - time.Now().Unix() - 1800
  49. // 确保最小有效期为0秒
  50. if durationSeconds < 0 {
  51. durationSeconds = 0
  52. }
  53. // 成功获取 token 后存入 Redis
  54. if setErr := t.rdb.SetEX(ctx, tokenKey, tokenData.AccessToken, time.Duration(durationSeconds)*time.Second).Err(); setErr != nil {
  55. log.Printf("Failed to set token in Redis: %v", setErr)
  56. }
  57. return tokenData.AccessToken, nil
  58. }
  59. log.Printf("获取hgApi token失败,剩余重试次数: %d, 错误: %v", maxRetries-i-1, err)
  60. if i < maxRetries-1 {
  61. time.Sleep(1 * time.Second)
  62. }
  63. }
  64. log.Println("hgApi token获取彻底失败,请检查接口状态")
  65. return "", fmt.Errorf("failed to get token after %d attempts", maxRetries)
  66. }
  67. func (t *TokenManager) requestToken() (structs.TokenData, error) {
  68. url := fmt.Sprintf("%s/gateway/oauth/token?grant_type=client_credentials&client_id=%s&client_secret=%s",
  69. t.apiUrl, t.hgConfig.Account, t.hgConfig.Password)
  70. respBytes, err := t.httpClient.RequestJSON(context.Background(), "GET", url, nil)
  71. if err != nil {
  72. return structs.TokenData{}, fmt.Errorf("HTTP请求失败: %w", err)
  73. }
  74. var tokenResp structs.TokenResponse
  75. if err := json.Unmarshal(respBytes, &tokenResp); err != nil {
  76. return structs.TokenData{}, fmt.Errorf("JSON解析失败: %w", err)
  77. }
  78. if !tokenResp.Success || tokenResp.Data.AccessToken == "" {
  79. return structs.TokenData{}, fmt.Errorf("接口返回无效响应")
  80. }
  81. return tokenResp.Data, nil
  82. }