Go项目优化——动态缓存Redis的使用

本文涉及的产品
Redis 开源版,标准版 2GB
推荐场景:
搭建游戏排行榜
云数据库 Tair(兼容Redis),内存型 2GB
简介: Go项目优化——动态缓存Redis的使用

1. Redis:

1.1 简介:

garyburd/redigo 包是网上很多博文都在推荐使用的一个高Star的Redis连接包,项目已经迁移到了gomodule/redigo,同时包的获取也理所当然地改成了go get github.com/gomodule/redigo/redis,总之,暂时不管这两个包的详细区别,以下就以新包为准,介绍下redigo包使用。

1.2 连接redis

//第一种连接方法
con,err := redis.Dial("tcp", 
  "链接地址,例如127.0.0.1:6379", 
  redis.DialPassword("密码"),
)
// or
// con,err := redis.Dial("tcp","127.0.0.1:6379")
if err != nil {
   fmt.Println(err)
}
defer con.Close()

1.3 常用api:

// Do 向服务器发送命令并返回收到的应答。
func Do(commandName string, args ...interface{}) (reply interface{}, err error)
// reply 具体类型,具体转换
func Int(reply interface{}, err error) (int, error) 
func String(reply interface{}, err error) (string, error)
func Bool(reply interface{}, err error) (bool, error) 
func Values(reply interface{}, err error) ([]interface{}, error) 
func Strings(reply interface{}, err error) ([]string, error)
func ByteSlices(reply interface{}, err error) ([][]byte, error)
func Ints(reply interface{}, err error) ([]int, error)
func StringMap(result interface{}, err error) (map[string]string, error)
...
// 更多函数自行探索

1.3 连接池

在golang的项目中,若要频繁的用redis(或者其他类似的NoSQL)来存取数据,最好用redigo自带的池来管理连接。

 不然的话,每当要操作redis时,建立连接,用完后再关闭,会导致大量的连接处于TIME_WAIT状态(redis连接本质上就是tcp)。

注:TIME_WAIT,也叫TCP半连接状态,会继续占用本地端口。

import (
  "fmt"
  "github.com/gomodule/redigo/redis"
  "time"
)
var redisPoll *redis.Pool
func initRedis() {
  redisPoll = &redis.Pool{
    // 连接方法
    Dial: func() (redis.Conn, error) {
      c, err := redis.Dial("tcp", "链接地址,例如127.0.0.1:6379",
        redis.DialPassword("密码"),
        redis.DialReadTimeout(1*time.Second),
        redis.DialWriteTimeout(1*time.Second),
        redis.DialConnectTimeout(1*time.Second),
      )
      if err != nil {
        return nil, err
      }
      return c, nil
    },
    // 最大的空闲连接数,
    // 表示即使没有redis连接时依然可以保持N个空闲的连接,而不被清除,随时处于待命状态。
    MaxIdle: 256,
    // 最大的激活连接数,表示同时最多有N个连接
    MaxActive: 256,
    // 最大的空闲连接等待时间,超过此时间后,空闲连接将被关闭
    IdleTimeout: time.Duration(120),
  }
}
// myDo
// @Title myDo
// @Description 封装的 redis Do函数
// Do(commandName string, args ...interface{}) (reply interface{}, err error)
// @Param cmd string 命令
// @Param key interface{} 键
// @Param args ...interface{} 参数
// @Return interface{} redis服务器返回值
// @Return error 错误
func myDo(cmd string, key interface{}, args ...interface{}) (interface{}, error) {
  // 从pool里获取一个redis连接,如果连接池没有,会调用 Dial()
  con := redisPoll.Get()
  if err := con.Err(); err != nil {
    return nil, err
  }
  parmas := make([]interface{}, 0)
  parmas = append(parmas, key)
  // 如果参数不为空,也加入参数列表
  if len(args) > 0 {
    for _, arg := range args {
      parmas = append(parmas, arg)
    }
  }
  return con.Do(cmd, parmas...)
}
func main() {
  initRedis()
  myDo("set", "mykey1", "myvalue1")
  result, err := myDo("get", "mykey1")
  if err != nil {
    fmt.Println(err.Error())
  }
  // String()是将命令应答转换为字符串的帮助器。
  str, _ := redis.String(result, err)
  fmt.Println(str)
}

1.4 项目中使用:

dynamic cache:动态缓存

conf/dynamicache.conf

#*******************
#动态缓存配置
#*******************
# redis地址
dynamicache_addrstr=127.0.0.1:6379
# redis密码
dynamicache_passwd=密码

conf/app.conf

...
# 引入动态缓存配置文件
include "dynamicache.conf"
...

utils/dynamic_cache.go

package dynamicache
import (
  "encoding/json"
  "github.com/astaxie/beego/logs"
  "strconv"
  "time"
  "github.com/astaxie/beego"
  "github.com/gomodule/redigo/redis"
)
var (
  pool *redis.Pool = nil
  // MaxIdle 最大的空闲连接数,
  MaxIdle int = 0
  // MaxOpen 最大的激活连接数,表示同时最多有N个连接
  MaxOpen int = 0
  // ExpireSec 超时时间
  ExpireSec int64 = 0
)
// InitCache 在 sysinit.go 中调用
// 初始化redis配置
func InitCache() {
  addr := beego.AppConfig.String("dynamicache_addrstr")
  if len(addr) == 0 {
    addr = "127.0.0.1:6379"
  }
  if MaxIdle <= 0 {
    MaxIdle = 256
  }
  password := beego.AppConfig.String("dynamicache_passwd")
  if len(password) == 0 {
    pool = &redis.Pool{
      MaxIdle:     MaxIdle,
      MaxActive:   MaxOpen, // 最大
      IdleTimeout: time.Duration(120),
      Dial: func() (redis.Conn, error) {
        return redis.Dial(
          "tcp",
          addr,
          redis.DialReadTimeout(1*time.Second),
          redis.DialWriteTimeout(1*time.Second),
          redis.DialConnectTimeout(1*time.Second),
        )
      },
    }
  } else {
    pool = &redis.Pool{
      MaxIdle:     MaxIdle,
      MaxActive:   MaxOpen,
      IdleTimeout: time.Duration(120),
      Dial: func() (redis.Conn, error) {
        return redis.Dial(
          "tcp",
          addr,
          redis.DialReadTimeout(1*time.Second),
          redis.DialWriteTimeout(1*time.Second),
          redis.DialConnectTimeout(1*time.Second),
          redis.DialPassword(password),
        )
      },
    }
  }
}

sysinit/sysinit.go

package sysinit
import (
    ...
  "mybook/utils/dynamicache"
  ...
)
....
// initDynamicCache
// @Title initDynamicCache
// @Description 初始化dynamic_cache.go里的公有值,并初始化redis配置 
func initDynamicCache() {
  dynamicache.MaxOpen = 128
  dynamicache.MaxIdle = 128
  dynamicache.ExpireSec = 10
  dynamicache.InitCache()
}
....

根据实际业务需要,在utils/dynamic_cache.go里封装会用到的方法

utils/dynamic_cache.go

...
// redisDo
// @Title redisDo
// @Description 封装的 redis Do函数
// Do(commandName string, args ...interface{}) (reply interface{}, err error)
// @Param cmd string 命令
// @Param key interface{} 键
// @Param args ...interface{} 参数
// @Return interface{} redis服务器返回值
// @Return error 错误
func redisDo(cmd string, key interface{}, args ...interface{}) (interface{}, error) {
  con := pool.Get()
  if err := con.Err(); err != nil {
    return nil, err
  }
  params := make([]interface{}, 0)
  params = append(params, key)
  if len(args) > 0 {
    for _, v := range args {
      params = append(params, v)
    }
  }
  return con.Do(cmd, params...)
}
// WriteString
// @Title WriteString
// @Description 写字符串
// @Param key string 键
// @Param value string 值
// @Return error 错误
func WriteString(key string, value string) error {
  _, err := redisDo("SET", key, value)
  logs.Debug("redis set:" + key + "-" + value)
  redisDo("EXPIRE", key, ExpireSec)
  return err
}
// ReadString
// @Title ReadString
// @Description  读字符串
// @Param key string 键
// @Param value string 值
// @Return error 错误
func ReadString(key string) (string, error) {
  result, err := redisDo("GET", key)
  logs.Debug("redis get:" + key)
  if nil == err {
    str, _ := redis.String(result, err)
    return str, nil
  } else {
    logs.Debug("redis get error:" + err.Error())
    return "", err
  }
}
// 以下封装的方法都是在WriteString() ReadString()上封装的,使用的都是redis里的string类型
// WriteStruct
// @Title WriteStruct
// @Description 写结构体(本质是还是写json字符串)
func WriteStruct(key string, obj interface{}) error {
  data, err := json.Marshal(obj)
  if nil == err {
    return WriteString(key, string(data))
  } else {
    return nil
  }
}
// ReadStruct
// @Title ReadStruct
// @Description 读结构体
func ReadStruct(key string, obj interface{}) error {
  if data, err := ReadString(key); nil == err {
    return json.Unmarshal([]byte(data), obj)
  } else {
    return err
  }
}
// WriteList
// @Title WriteList
// @Description 写数组
func WriteList(key string, list interface{}, total int) error {
  realKeyList := key + "_list"
  realKeyCount := key + "_count"
  data, err := json.Marshal(list)
  if nil == err {
    WriteString(realKeyCount, strconv.Itoa(total))
    return WriteString(realKeyList, string(data))
  } else {
    return nil
  }
}
// ReadList
// @Title ReadList
// @Description 读数组
func ReadList(key string, list interface{}) (int, error) {
  realKeyList := key + "_list"
  realKeyCount := key + "_count"
  if data, err := ReadString(realKeyList); nil == err {
    totalStr, _ := ReadString(realKeyCount)
    total := 0
    if len(totalStr) > 0 {
      total, _ = strconv.Atoi(totalStr)
    }
    return total, json.Unmarshal([]byte(data), list)
  } else {
    return 0, err
  }
}
相关文章
|
2月前
|
存储 机器学习/深度学习 缓存
性能最高提升7倍?探究大语言模型推理之缓存优化
本文探讨了大语言模型(LLM)推理缓存优化技术,重点分析了KV Cache、PagedAttention、Prefix Caching及LMCache等关键技术的演进与优化方向。文章介绍了主流推理框架如vLLM和SGLang在提升首Token延迟(TTFT)、平均Token生成时间(TPOT)和吞吐量方面的实现机制,并展望了未来缓存技术的发展趋势。
性能最高提升7倍?探究大语言模型推理之缓存优化
|
17天前
|
消息中间件 缓存 NoSQL
Redis各类数据结构详细介绍及其在Go语言Gin框架下实践应用
这只是利用Go语言和Gin框架与Redis交互最基础部分展示;根据具体业务需求可能需要更复杂查询、事务处理或订阅发布功能实现更多高级特性应用场景。
144 86
|
4月前
|
缓存 NoSQL 关系型数据库
美团面试:MySQL有1000w数据,redis只存20w的数据,如何做 缓存 设计?
美团面试:MySQL有1000w数据,redis只存20w的数据,如何做 缓存 设计?
美团面试:MySQL有1000w数据,redis只存20w的数据,如何做 缓存 设计?
|
9天前
|
存储 缓存 NoSQL
Redis专题-实战篇二-商户查询缓存
本文介绍了缓存的基本概念、应用场景及实现方式,涵盖Redis缓存设计、缓存更新策略、缓存穿透问题及其解决方案。重点讲解了缓存空对象与布隆过滤器的使用,并通过代码示例演示了商铺查询的缓存优化实践。
69 1
Redis专题-实战篇二-商户查询缓存
|
9天前
|
缓存 Java 应用服务中间件
Spring Boot配置优化:Tomcat+数据库+缓存+日志,全场景教程
本文详解Spring Boot十大核心配置优化技巧,涵盖Tomcat连接池、数据库连接池、Jackson时区、日志管理、缓存策略、异步线程池等关键配置,结合代码示例与通俗解释,助你轻松掌握高并发场景下的性能调优方法,适用于实际项目落地。
159 4
|
4月前
|
缓存 NoSQL Java
Redis+Caffeine构建高性能二级缓存
大家好,我是摘星。今天为大家带来的是Redis+Caffeine构建高性能二级缓存,废话不多说直接开始~
706 0
|
9天前
|
缓存 NoSQL 关系型数据库
Redis缓存和分布式锁
Redis 是一种高性能的键值存储系统,广泛用于缓存、消息队列和内存数据库。其典型应用包括缓解关系型数据库压力,通过缓存热点数据提高查询效率,支持高并发访问。此外,Redis 还可用于实现分布式锁,解决分布式系统中的资源竞争问题。文章还探讨了缓存的更新策略、缓存穿透与雪崩的解决方案,以及 Redlock 算法等关键技术。
|
5月前
|
缓存 并行计算 PyTorch
PyTorch CUDA内存管理优化:深度理解GPU资源分配与缓存机制
本文深入探讨了PyTorch中GPU内存管理的核心机制,特别是CUDA缓存分配器的作用与优化策略。文章分析了常见的“CUDA out of memory”问题及其成因,并通过实际案例(如Llama 1B模型训练)展示了内存分配模式。PyTorch的缓存分配器通过内存池化、延迟释放和碎片化优化等技术,显著提升了内存使用效率,减少了系统调用开销。此外,文章还介绍了高级优化方法,包括混合精度训练、梯度检查点技术及自定义内存分配器配置。这些策略有助于开发者在有限硬件资源下实现更高性能的深度学习模型训练与推理。
998 0
|
2月前
|
存储 缓存 NoSQL
Redis 核心知识与项目实践解析
本文围绕 Redis 展开,涵盖其在项目中的应用(热点数据缓存、存储业务数据、实现分布式锁)、基础数据类型(string 等 5 种)、持久化策略(RDB、AOF 及混合持久化)、过期策略(惰性 + 定期删除)、淘汰策略(8 种分类)。 还介绍了集群方案(主从复制、哨兵、Cluster 分片)及主从同步机制,分片集群数据存储的哈希槽算法。对比了 Redis 与 Memcached 的区别,说明了内存用完的情况及与 MySQL 数据一致性的保证方案。 此外,详解了缓存穿透、击穿、雪崩的概念及解决办法,如何保证 Redis 中是热点数据,Redis 分布式锁的实现及问题解决,以及项目中分布式锁
|
2月前
|
监控 Java 编译器
限流、控并发、减GC!一文搞懂Go项目资源优化的正确姿势
本章介绍Go语言项目在构建与部署阶段的性能调优和资源控制策略,涵盖编译优化、程序性能提升、并发与系统资源管理、容器化部署及自动化测试等内容,助力开发者打造高效稳定的生产级应用。