Go-Redis

作者: 陈光环_18 | 来源:发表于2021-06-07 12:59 被阅读0次

Redis支持的数据结构

Redis支持诸如字符串(strings)、哈希(hashes)、列表(lists)、集合(sets)、带范围查询的排序集合(sorted sets)、位图(bitmaps)、hyperloglogs、带半径查询和流的地理空间索引等数据结构(geospatial indexes)。

Redis应用场景

缓存系统,减轻主数据库(MySQL)的压力。
计数场景,比如微博、抖音中的关注数和粉丝数。
热门排行榜,需要排序的场景特别适合使用ZSET。
利用LIST可以实现队列的功能。

Redis与Memcached比较

Memcached中的值只支持简单的字符串,Reids支持更丰富的5中数据结构类型。
Redis的性能比Memcached好很多
Redis支持RDB持久化和AOF持久化。
Redis支持master/slave模式。

操作步骤

下载依赖

go get github.com/garyburd/redigo/redis

创建连接

conn, err := redis.Dial("tcp",
"127.0.0.1:6379",
redis.DialDatabase(1) // dialOption参数可以配置选择数据库、连接密码、心跳检测等等
redis.DialPassword("xxxx"))
if err != nil {
fmt.Println("Connect to redis failed ,cause by >>>", err)
return
}
defer conn.Close()

插入值

//写入值
_, err = conn.Do("SET", "test-Key", "test-Value")
if err != nil {
fmt.Println("redis set value failed >>>", err)
}

检验key值是否存在

//检查是否存在key值
exists, err := redis.Bool(conn.Do("EXISTS", "test-Key"))
if err != nil {
fmt.Println("illegal exception")
}
fmt.Printf("exists or not: %v \n", exists)

获取值

//read value
v, err := redis.String(conn.Do("GET", "test-Key"))
if err != nil {
fmt.Println("redis get value failed >>>", err)
}
fmt.Println("get value: ", v)

给定一个kv的过期时间

//EX,5秒
_, err = conn.Do("SET", "test-Key", "test-Value", "EX", "5")
if err != nil {
fmt.Println("redis set value failed >>>", err)
}

删除key

//del kv
_, err = conn.Do("DEL", "test-Key")
if err != nil {
fmt.Println("redis delelte value failed >>>", err)
}

相关文章

  • golang操作redis

    项目依赖地址go-redis https://github.com/go-redis/redis[https://...

  • go-redis 源码分析:连接池

    笔者最近在项目中基于 go-redis 实现 Redis 缓存优化性能。go-redis 是一个 Go 语言实现的...

  • go操作redis cluster集群

    github.com/go-redis/redis 非常友好的SDK

  • Go-Redis

    Redis支持的数据结构 Redis支持诸如字符串(strings)、哈希(hashes)、列表(lists)、集...

  • Go-redis

    Redis 优势 性能极高 – Redis能读的速度是110000次/s,写的速度是81000次/s ,单机能够达...

  • Golang使用Redis

    go使用Redis 文档链接:https://godoc.org/github.com/go-redis/redis

  • Redis在Go中的应用

    转自 http://witchiman.github.io/2017/04/14/go-redis Go 作为一种...

  • go-redis options

    github.com/go-redis/redis options配置 其中要特别注意MaxConnAge,默认值...

  • golang-redis(1)

    一、redis连接 引入包"github.com/go-redis/redis/v8" var( redisIns...

  • go-redis使用

    一。连接,设值,取值,设置过期时间

网友评论

      本文标题:Go-Redis

      本文链接:https://www.haomeiwen.com/subject/bfjleltx.html