Go语言中文文档-08数据操作-go操作Redis

Redis介绍

安装go-Redis依赖,不go mod init(创建.mod文件)会出错。
安装Redis: brew install redis
启动Redis:
//方式一:使用brew帮助我们启动软件
brew services start redis
//方式二
redis-server /usr/local/etc/redis.conf
查看Redis是否在运行:
ps axu | grep redis
关闭redis服务:
redis-cli shutdown
强行终止:
sudo pkill redis-server
redis.conf 配置文件详解
redis默认是前台启动,如果我们想以守护进程的方式运行(后台运行),可以在redis.conf中将daemonize no,修改成yes即可。

与Redis建立连接:

c, err := redis.Dial("tcp", "localhost:6379")

对Redis传命令:

_, err = c.Do("Set", "abc", 100)

取Redis数据

r, err := redis.Int(c.Do("Get", "abc"))

redis连接池

创建Redis连接池:
var pool *redis.Pool //创建redis连接池
实例化Redis连接池:

点击查看代码
func init() {
	pool = &redis.Pool{ //实例化一个连接池
		MaxIdle: 16, //最初的连接数量
		// MaxActive:1000000,    //最大连接数量
		MaxActive:   0,   //连接池最大连接数量,不确定可以用0(0表示自动定义),按需分配
		IdleTimeout: 300, //连接关闭时间 300秒 (300秒不使用自动关闭)
		Dial: func() (redis.Conn, error) { //要连接的redis数据库
			return redis.Dial("tcp", "localhost:6379")
		},
	}
}

取一个连接:
c := pool.Get()

posted @ 2022-03-25 19:26  人生hh  阅读(270)  评论(0)    收藏  举报