RedisStore.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. // Author: simon (ynwdlxm@163.com)
  2. // Date: 2025/7/21 09:56
  3. // Desc: redis 缓存,实现 Store 接口
  4. package cache
  5. import (
  6. "time"
  7. "github.com/runningwater/gohub/pkg/config"
  8. "github.com/runningwater/gohub/pkg/redis"
  9. )
  10. type RedisStore struct {
  11. RedisClient *redis.Client
  12. KeyPrefix string
  13. }
  14. func NewRedisStore(address, username, password string, db int) *RedisStore {
  15. rs := &RedisStore{
  16. RedisClient: redis.NewClient(address, username, password, db),
  17. KeyPrefix: config.GetString("app.name") + ":cache:",
  18. }
  19. return rs
  20. }
  21. func (r *RedisStore) Set(key, value string, expire time.Duration) {
  22. r.RedisClient.Set(r.KeyPrefix+key, value, expire)
  23. }
  24. func (r *RedisStore) Get(key string) string {
  25. return r.RedisClient.Get(r.KeyPrefix + key)
  26. }
  27. func (r *RedisStore) Has(key string) bool {
  28. return r.RedisClient.Has(r.KeyPrefix + key)
  29. }
  30. func (r *RedisStore) Forget(key string) {
  31. r.RedisClient.Del(r.KeyPrefix + key)
  32. }
  33. func (r *RedisStore) Forever(key, value string) {
  34. r.RedisClient.Set(r.KeyPrefix+key, value, 0)
  35. }
  36. func (r *RedisStore) Flush() {
  37. r.RedisClient.FlushDb()
  38. }
  39. func (r *RedisStore) IsAlive() error {
  40. return r.RedisClient.Ping()
  41. }
  42. func (r *RedisStore) Increment(params ...any) {
  43. r.RedisClient.Increment(params)
  44. }
  45. func (r *RedisStore) Decrement(params ...any) {
  46. r.RedisClient.Decrement(params)
  47. }