cache.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  1. package cache
  2. import (
  3. "encoding/json"
  4. "git.sxidc.com/go-tools/utils/reflectutils"
  5. "git.sxidc.com/go-tools/utils/strutils"
  6. "github.com/pkg/errors"
  7. "reflect"
  8. "strconv"
  9. "strings"
  10. "time"
  11. )
  12. // Cache 缓存基础设施接口
  13. type Cache interface {
  14. // Set 设置缓存值
  15. Set(key string, value string, expireSec int64) error
  16. // Get 获取缓存值
  17. Get(key string) (string, error)
  18. // GetMulti 获取多个缓存值
  19. GetMulti(keys []string) (map[string]string, error)
  20. // GetAll 获取所有缓存值
  21. GetAll() (map[string]string, error)
  22. // Delete 删除缓存值
  23. Delete(key string) error
  24. // Clear 清除缓存
  25. Clear() error
  26. // Expire 使用秒数设置key的过期时间
  27. Expire(key string, expireSec int64) error
  28. // ExpireTime 获取过期秒数
  29. ExpireTime(key string) (int64, error)
  30. // TTL 获取过期剩余秒数
  31. TTL(key string) (int64, error)
  32. }
  33. // Set 设置缓存值
  34. // 参数:
  35. // - cache: 缓存基础设施接口
  36. // - key: 缓存的键
  37. // - value: 要设置的缓存值
  38. // - expireSec: 缓存过期时间,单位秒
  39. // 返回值:
  40. // - 错误
  41. func Set(cache Cache, key string, value any, expireSec int64) error {
  42. valueReflectValue := reflect.ValueOf(value)
  43. if !valueReflectValue.IsValid() {
  44. return errors.New("缓存值无效")
  45. }
  46. stringValue, err := toString(valueReflectValue)
  47. if err != nil {
  48. return err
  49. }
  50. return cache.Set(key, stringValue, expireSec)
  51. }
  52. // Get 获取缓存值
  53. // 泛型参数:
  54. // - T: 缓存值类型
  55. // 参数:
  56. // - cache: 缓存基础设施接口
  57. // - key: 缓存的键
  58. // 返回值:
  59. // - 缓存值
  60. // - 错误
  61. func Get[T any](cache Cache, key string) (T, error) {
  62. var zero T
  63. stringValue, err := cache.Get(key)
  64. if err != nil {
  65. return zero, err
  66. }
  67. retValue := reflectutils.Zero[T]()
  68. retValueReflectType := reflect.TypeOf(retValue)
  69. if retValueReflectType.Kind() == reflect.Pointer {
  70. err := fromString(stringValue, retValue)
  71. if err != nil {
  72. return zero, err
  73. }
  74. } else {
  75. err := fromString(stringValue, &retValue)
  76. if err != nil {
  77. return zero, err
  78. }
  79. }
  80. return retValue, nil
  81. }
  82. // GetMulti 批量获取缓存值
  83. // 参数:
  84. // - cache: 缓存基础设施接口
  85. // - keys: 缓存的键(多个)
  86. // 返回值:
  87. // - 缓存值,value以string类型先返回
  88. // - 错误
  89. func GetMulti(cache Cache, keys []string) (map[string]string, error) {
  90. return cache.GetMulti(keys)
  91. }
  92. // GetAll 获取所有缓存值
  93. // 参数:
  94. // - cache: 缓存基础设施接口
  95. // 返回值:
  96. // - 缓存值,value以string类型先返回
  97. // - 错误
  98. func GetAll(cache Cache) (map[string]string, error) {
  99. return cache.GetAll()
  100. }
  101. // Delete 删除缓存值
  102. // 参数:
  103. // - cache: 缓存基础设施接口
  104. // - key: 缓存的键
  105. // 返回值:
  106. // - 错误
  107. func Delete(cache Cache, key string) error {
  108. return cache.Delete(key)
  109. }
  110. // Clear 清除缓存
  111. // 参数:
  112. // - cache: 缓存基础设施接口
  113. // 返回值:
  114. // - 错误
  115. func Clear(cache Cache) error {
  116. return cache.Clear()
  117. }
  118. // Expire 使用秒数设置key的过期时间
  119. // 参数:
  120. // - cache: 缓存基础设施接口
  121. // - expireSec: 缓存过期时间,单位秒
  122. // 返回值:
  123. // - 错误
  124. func Expire(cache Cache, key string, expireSec int64) error {
  125. return cache.Expire(key, expireSec)
  126. }
  127. // ExpireTime 获取过期秒数
  128. // 参数:
  129. // - cache: 缓存基础设施接口
  130. // - key: 缓存的键
  131. // 返回值:
  132. // - 过期秒数
  133. // - 错误
  134. func ExpireTime(cache Cache, key string) (int64, error) {
  135. return cache.ExpireTime(key)
  136. }
  137. // TTL 获取过期剩余秒数
  138. // 参数:
  139. // - cache: 缓存基础设施接口
  140. // - key: 缓存的键
  141. // 返回值:
  142. // - 剩余过期秒数
  143. // - 错误
  144. func TTL(cache Cache, key string) (int64, error) {
  145. return cache.TTL(key)
  146. }
  147. func toString(valueReflectValue reflect.Value) (string, error) {
  148. dataVal := reflect.Indirect(valueReflectValue)
  149. dataKind := reflectutils.GroupValueKind(dataVal)
  150. switch dataKind {
  151. case reflect.String:
  152. return dataVal.String(), nil
  153. case reflect.Bool:
  154. if dataVal.Bool() {
  155. return "true", nil
  156. } else {
  157. return "false", nil
  158. }
  159. case reflect.Int64:
  160. return strconv.FormatInt(dataVal.Int(), 10), nil
  161. case reflect.Uint64:
  162. return strconv.FormatUint(dataVal.Uint(), 10), nil
  163. case reflect.Float64:
  164. return strconv.FormatFloat(dataVal.Float(), 'f', -1, 64), nil
  165. case reflect.Slice, reflect.Array:
  166. dataElementType := reflectutils.PointerTypeElem(dataVal.Type().Elem())
  167. // []byte,直接转换为string
  168. if dataElementType.Kind() == reflect.Uint8 {
  169. if dataVal.Len() == 0 {
  170. return "", nil
  171. }
  172. uints := make([]uint8, dataVal.Len(), dataVal.Len())
  173. for i := 0; i < dataVal.Len(); i++ {
  174. uints[i] = dataVal.Index(i).Interface().(uint8)
  175. }
  176. return string(uints), nil
  177. } else {
  178. if dataVal.Len() == 0 {
  179. return "[]", nil
  180. }
  181. stringBuilder := strings.Builder{}
  182. stringBuilder.WriteString("[")
  183. for i := 0; i < dataVal.Len(); i++ {
  184. strValue, err := toString(dataVal.Index(i))
  185. if err != nil {
  186. return "", err
  187. }
  188. if i > 0 {
  189. stringBuilder.WriteString(",")
  190. }
  191. stringBuilder.WriteString(strValue)
  192. }
  193. stringBuilder.WriteString("]")
  194. return stringBuilder.String(), nil
  195. }
  196. case reflect.Map, reflect.Struct:
  197. if dataVal.Type().Name() == "time.Time" {
  198. return dataVal.Interface().(time.Time).Format(time.RFC3339Nano), nil
  199. } else {
  200. jsonBytes, err := json.Marshal(dataVal.Interface())
  201. if err != nil {
  202. return "", errors.New(err.Error())
  203. }
  204. return string(jsonBytes), nil
  205. }
  206. default:
  207. return "", errors.New("不支持的缓存值类型: " + dataVal.Type().Elem().String())
  208. }
  209. }
  210. func fromString(stringValue string, retValue any) error {
  211. retValueReflectValue := reflect.ValueOf(retValue)
  212. if retValueReflectValue.Kind() != reflect.Pointer {
  213. return errors.New("返回值不是指针类型")
  214. }
  215. dataVal := reflect.Indirect(retValueReflectValue)
  216. dataKind := reflectutils.GroupValueKind(dataVal)
  217. switch dataKind {
  218. case reflect.String:
  219. dataVal.SetString(stringValue)
  220. return nil
  221. case reflect.Bool:
  222. if strutils.IsStringEmpty(stringValue) {
  223. dataVal.SetBool(false)
  224. } else {
  225. if stringValue == "false" {
  226. dataVal.SetBool(false)
  227. } else {
  228. dataVal.SetBool(true)
  229. }
  230. }
  231. return nil
  232. case reflect.Int64:
  233. intValue, err := strconv.ParseInt(stringValue, 10, 64)
  234. if err != nil {
  235. return errors.New(err.Error())
  236. }
  237. dataVal.SetInt(intValue)
  238. return nil
  239. case reflect.Uint64:
  240. uintValue, err := strconv.ParseUint(stringValue, 10, 64)
  241. if err != nil {
  242. return err
  243. }
  244. dataVal.SetUint(uintValue)
  245. return nil
  246. case reflect.Float64:
  247. floatValue, err := strconv.ParseFloat(stringValue, 64)
  248. if err != nil {
  249. return err
  250. }
  251. dataVal.SetFloat(floatValue)
  252. return nil
  253. case reflect.Slice, reflect.Array:
  254. dataElementType := reflectutils.PointerTypeElem(dataVal.Type().Elem())
  255. // []byte直接用string赋值
  256. if dataElementType.Kind() == reflect.Uint8 {
  257. dataSliceVal := reflect.MakeSlice(dataVal.Type(), 0, 0)
  258. for _, b := range []byte(stringValue) {
  259. if dataVal.Type().Elem().Kind() == reflect.Pointer {
  260. dataSliceVal = reflect.Append(dataSliceVal, reflect.ValueOf(&b))
  261. } else {
  262. dataSliceVal = reflect.Append(dataSliceVal, reflect.ValueOf(b))
  263. }
  264. }
  265. dataVal.Set(dataSliceVal)
  266. return nil
  267. } else {
  268. if !strings.HasPrefix(stringValue, "[") || !strings.HasSuffix(stringValue, "]") {
  269. return errors.New("缓存值不是切片或数组形式")
  270. }
  271. dataSliceVal := reflect.MakeSlice(dataVal.Type(), 0, 0)
  272. stringValue = strings.TrimSuffix(strings.TrimPrefix(stringValue, "["), "]")
  273. stringValueParts := strings.Split(stringValue, ",")
  274. for _, strValuePart := range stringValueParts {
  275. dataSliceElementType := dataVal.Type().Elem()
  276. dataSliceElementVal := reflect.Indirect(reflect.New(dataSliceElementType))
  277. if dataSliceElementVal.Kind() == reflect.Pointer {
  278. dataSliceElementVal.Set(reflect.New(dataSliceElementVal.Type().Elem()))
  279. err := fromString(strValuePart, dataSliceElementVal.Interface())
  280. if err != nil {
  281. return err
  282. }
  283. } else {
  284. err := fromString(strValuePart, dataSliceElementVal.Addr().Interface())
  285. if err != nil {
  286. return err
  287. }
  288. }
  289. dataSliceVal = reflect.Append(dataSliceVal, dataSliceElementVal)
  290. }
  291. dataVal.Set(dataSliceVal)
  292. return nil
  293. }
  294. case reflect.Map, reflect.Struct:
  295. if dataVal.Type().Name() == "time.Time" {
  296. parsedTime, err := time.ParseInLocation(time.RFC3339Nano, stringValue, time.Local)
  297. if err != nil {
  298. return err
  299. }
  300. dataVal.Set(reflect.ValueOf(parsedTime))
  301. return nil
  302. } else {
  303. err := json.Unmarshal([]byte(stringValue), dataVal.Addr().Interface())
  304. if err != nil {
  305. return errors.New(err.Error())
  306. }
  307. return nil
  308. }
  309. default:
  310. return errors.New("不支持的缓存值类型: " + dataVal.Type().Elem().String())
  311. }
  312. }