账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    go语言中的Redis缓存相关代码接口的设计
    47
    0

    系统中有一些数据量不大且几乎不变的的数据表,数据表命名都以"L_"开头,以下简称L表。
    需求:通过Redis缓存将L表数据缓存起来以提升系统响应速度
    目前设计方案:

    1. 初始Redis时全量缓存
    2. Redis存储数据结构为K-V,

    Key := TableName : id : name
    通过这样设计Key的方式用以支持FindByID和FindByName的模糊查询
    目前get方法的设计如下:

    func GetData(key string) (string, error) {
        return Get(key)
    }
    
    func GetKeys(pattern string) ([]string, error) {
        return Keys(pattern)
    }
    
    func FindById(table_name string, id int64) (string, error) {
        var q Query
        q.TableName = table_name
        q.ID = id
        pattern := q.TableName + ":" + strconv.FormatInt(q.ID, 10) + "*"
        key, _ := GetKeys(pattern)
        return GetData(key[0])
    }

    问题:

    本人Go和Redis都是初学,做了如上设计,但是由于后期需要FindBy更多字段,由于表格式的变换,Query的数据类型也有多种可能,现在的设计难以支持扩展,想问下大家相关设计经验,我应该怎样设计Get方法更好?
    还望大家不吝赐教,谢谢大家!

    0
    打赏
    收藏
    点击回答
        全部回答
    • 0
    • 遠赱┈肆方 普通会员 1楼

      在Go语言中,Redis是一个流行的数据结构存储系统,可以用来缓存数据。以下是一个简单的Redis缓存接口的设计:

      ```go package main

      import ( "context" "fmt" "time"

      "github.com/go-redis/redis/v8"
      

      )

      type RedisCache interface { // Add(key string, value interface{}) error Store(key string, value interface{}) error

      // Get(key string) interface{}
      Load(key string) interface{}
      

      }

      // RedisStore provides the Redis storage interface. type RedisStore struct { *redis.Client }

      func NewRedisStore(c redis.Client) RedisStore { return &RedisStore{ *c, } }

      // RedisGet provides the Redis get interface. func (rs *RedisStore) Get(key string) interface{} { return rs.Client.Get(key) }

      // RedisStore提供Redis存储接口。 func (rs *RedisStore) Store(key string, value interface{}) error { return rs.Client.Set(key, value) }

      // RedisGet提供Redis get接口。 func (rs *RedisStore) Load(key string) interface{} { return rs.Client.Get(key) } ```

      这个接口定义了三种操作:添加数据到Redis缓存、从Redis缓存中获取数据以及将数据从Redis缓存中移除。每个操作都有一个对应的实现。

      注意,这个接口并不是完全封闭的,它提供了一些公共的方法,例如NewRedisStoreGet,这些方法在创建Redis缓存和从Redis缓存中获取数据时使用。

      此外,这个接口只是一个基本的实现,实际的Redis缓存可能会更复杂,例如,它可能会包含一些额外的逻辑来处理错误、处理连接问题等。

    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部