Tokey.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. package Account
  2. import (
  3. "Cold_mqtt/conf"
  4. "Cold_mqtt/logs"
  5. "fmt"
  6. "github.com/astaxie/beego/cache"
  7. _ "github.com/astaxie/beego/cache/redis"
  8. uuid "github.com/satori/go.uuid"
  9. "time"
  10. )
  11. var redisCache_Tokey cache.Cache
  12. func init() {
  13. //注册模型
  14. //orm.RegisterModel(new(Tokey))
  15. config := fmt.Sprintf(`{"key":"%s","conn":"%s","dbNum":"%s","password":"%s"}`,
  16. "redis_User_Tokey", conf.Redis_address, conf.Redis_dbNum, conf.Redis_password)
  17. var err error
  18. redisCache_Tokey, err = cache.NewCache("redis", config)
  19. if err != nil || redisCache_Tokey == nil {
  20. errMsg := "failed to init redis"
  21. logs.PrintlnError(errMsg, err)
  22. }
  23. }
  24. // ---------------- Redis -------------------
  25. // Redis_Set(m.T_sn,m) // Redis 更新缓存
  26. func Add_Tokey_Set(Uuid string) string {
  27. var Tokey string
  28. for true {
  29. Tokey = uuid.NewV4().String()
  30. if !redisCache_Tokey.IsExist(Tokey) {
  31. break
  32. }
  33. fmt.Print("申请 TOKEY 重复!重新生成。", Tokey)
  34. }
  35. redisCache_Tokey.Put(Tokey, Uuid, 2*time.Hour)
  36. return Tokey
  37. }
  38. // if r,is :=Redis_Get(T_sn);is{
  39. // return r,nil
  40. // }
  41. func Redis_Tokey_Get(Tokey string) (string, bool) {
  42. if len(Tokey) < 10 {
  43. return "", false
  44. }
  45. if redisCache_Tokey.IsExist(Tokey) {
  46. //println("找到key:",key)
  47. v := redisCache_Tokey.Get(Tokey)
  48. value := string(v.([]byte)) //这里的转换很重要,Get返回的是interface
  49. redisCache_Tokey.Put(Tokey, value, 2*time.Hour) // 重新计次
  50. return value, true
  51. }
  52. //println("没有 找到key:",key)
  53. return "", false
  54. }