gin框架学习四之redis

在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()

402a37eed50b432eb631e38b2fb5f53a.png

 在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

 

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值