周五上班的主要任务是在公司老平台上用redis处理一个队列问题,顺便复习了一下redis操作的基础知识,回来后就想着在自己的博客demo里,用redis来优化一些使用场景,学习一下golang开发下redis的使用。
Redis简单介绍
简介
关于Redis的讨论,其实在现在的后台开发中已经是个老生常谈的问题,基本上也是后端开发面试的基本考察点。其中 Redis的背景介绍和细节说明在这里就不赘述。不管怎么介绍,核心在于Redis是一个基于内存的key-value的多数据结构存储,并可以提供持久化服务。基于内存的特性决定了Redis天然适合高并发的数据读写缓存优化,同时也带来了内存开销过大的问题。所以在一些特定情景下,Redis是一把无往不利的大杀器,值得深入学习。
RedissqlRedisRedis
主要数据结构
Redis主要有五种基本数据结构,满足了绝大多数缓存结构的需要,如果你在使用一种结构存储时感觉别扭时,很有可能是选错了存储结构,可以考虑一下其他结构的正确实现。
stringHashLPUSHLPOPRPUSHRPOPScore
常见使用场景
redisredisredisredisrediskeyapiredisINCRBY
Golang连接Redis
Golang
garyburd/redigo 包简介
garyburd/redigoRedisGithubAPIgo get github.com/gomodule/redigo/redisdepdepAPIredigo
建立连接池
redis
pool := &redis.Pool{
MaxIdle: 3, /*最大的空闲连接数*/
MaxActive: 8, /*最大的激活连接数*/
Dial: func() (redis.Conn, error) {
c, err := redis.Dial("tcp", "链接地址,例如127.0.0.1:6379", redis.DialPassword("密码"))
if err != nil {
return nil, err
}
return c, nil
},
}
c:=pool.Get()
defer c.Close()
执行指令
Conn
//gomodule/redigo/redis/redis.go
// Conn represents a connection to a Redis server.
type Conn interface {
// Close closes the connection.
Close() error
// Err returns a non-nil value when the connection is not usable.
Err() error
// Do sends a command to the server and returns the received reply.
Do(commandName string, args ...interface{}) (reply interface{}, err error)
// Send writes the command to the client's output buffer.
Send(commandName string, args ...interface{}) error
// Flush flushes the output buffer to the Redis server.
Flush() error
// Receive receives a single reply from the Redis server
Receive() (reply interface{}, err error)
}
doredis-cliSET key value EX 360Do("SET", "key", "value","EX",360)
c:=pool.Get()
defer c.Close()
//存值,
_, err := c.Do("SET", "key", "value")
//设置过期时间
_, err := c.Do("SET", "key", "value","EX",360)
//存int
_, err := c.Do("SET", "key", 2)
//取值
v,err:=redis.String(c.Do("GET","key"))
bytes, err := redis.Bytes(c.Do("GET", "key"))
总结
golangredisredis-cli