在app目录新建cache文件夹 ,然后在cache文件夹下新建cache.go 来初始化 redisClient。代码如下
使用的是 github.com/go-redis/redis
import ( "fmt" "ginApi/conf" "github.com/go-redis/redis" "time" ) var RedisClient *redis.Client func InitRedis(config *conf.RedisConfig) { addr := config.Host+ ":" +config.Port RedisClient = redis.NewClient(&redis.Options{ Addr: addr, // Redis地址 Password: config.Password, // Redis账号 DB: config.Db, // Redis库 PoolSize: 10, // Redis连接池大小 MaxRetries: 3, // 最大重试次数 IdleTimeout: 10*time.Second, // 空闲链接超时时间 }) pong, err := RedisClient.Ping().Result() if err == redis.Nil { fmt.Print("Redis异常") } else if err != nil { fmt.Print("失败:",err) } else { fmt.Print(pong) } }
在main.go 中调用 cache.InitRedis()
在cache文件夹下分别有五个文件 ,针对常用的redis的五种数据类型的简单操作
product_cache.go 使用string 类型
// redis string 使用 func (c *ProductCache) Key(id int) string { return "product:pk:id" + strconv.Itoa(id) } func (c *ProductCache) Set(id int,model *model.Product,expire time.Duration) bool { key := c.Key(id) bytes ,_ := json.Marshal(model) _,err := RedisClient.Set(key,bytes,120*time.Second).Result() if err != nil { fmt.Println("redis set error:",err) return false } return true } func (c *ProductCache) Get (id int) *model.Product { key := c.Key(id) res,err := RedisClient.Get(key).Result() if err != nil { return nil } var data *model.Product _ = json.Unmarshal([]byte(res),&data) return data } func (c *ProductCache) Del (id int) bool { _,err := RedisClient.Del(c.Key(id)).Result() if err != nil { return false } return true }
black_list.go set 数据类型的使用
//redis set 的 使用 set 查找 添加 删除的复杂度都是 O(1) //模拟一个ip黑名单 使用redis的set数据类型 ,因为set集合 成员不可以重复 func (c *BlackListCache) Key() string { return "BlackList:ip" } //set 中添加一个成员 func (c *BlackListCache) SAdd(ip string) bool { key := c.Key() _,err :=RedisClient.SAdd(key,ip).Result() if err != nil { fmt.Println("redis SAdd error:",err) return false } return true } //set 中删除一个成员 func (c *BlackListCache) SRem (ip string) bool { key := c.Key() _,err :=RedisClient.SRem(key,ip).Result() if err != nil { fmt.Println("redis SRem error:",err) return false } return true } //set 中是否存在某个成员 func (c *BlackListCache) SIsMember(ip string) bool { key := c.Key() _,err := RedisClient.SIsMember(key,ip).Result() if err != nil { fmt.Println("redis SAdd error:",err) return false } return true }
其余代码详细可见git 地址
GitHub - hailin86/ginApi at redis