Golang 入门系列(七) Redis的使用
前面已经讲过一些Go语言的基础知识,感兴趣的朋友可以先看看之前的文章。https://www.cnblogs.com/zhangweizhong/category/1275863.html。
今天就来讲讲go 里面的如何使用 Redis。
安装
import "github.com/go-redis/redis"
基本操作
创建Redis连接客户端
func GetRedisClient() *Client {
redisdb := NewClient(&Options{
Addr: "127.0.0.1:6379",
Password: "", // no password set
DB: , // use default DB
})
pong, err := redisdb.Ping().Result()
if err != nil {
fmt.Println(pong, err)
}
return redisdb
}
通过 cient.Ping() 来检查是否成功连接到了 redis 服务器
String 操作
func StringDemo() {
fmt.Println("-----------------------welcome to StringDemo-----------------------")
redisClient:=GetRedisClient()
if redisClient ==nil{
fmt.Errorf("StringDemo redisClient is nil")
return
}
name := "张三"
key :="name:zhangsan"
redisClient.Set(key , name, * time.Second)
val := redisClient.Get(key)
if val == nil {
fmt.Errorf("StringDemo get error")
}
fmt.Println("name", val)
}
List 操作
func ListDemo(){
fmt.Println("-----------------------welcome to ListDemo-----------------------")
redisClient:=GetRedisClient()
if redisClient == nil {
fmt.Errorf("ListDemo redisClient is nil")
return
}
articleKey := "article"
result,err:=redisClient.RPush(articleKey, "a","b","c").Result() //
if err!=nil {
fmt.Println(err)
return
}
fmt.Println("result:",result)
result,err = redisClient.LPush(articleKey, "d").Result() //
if err!=nil {
fmt.Println(err)
return
}
fmt.Println("result:",result)
length, err := redisClient.LLen(articleKey).Result()
if err != nil {
fmt.Println("ListDemo LLen is nil")
}
fmt.Println("length: ", length) // 长度
mapOut,err1:=redisClient.LRange(articleKey,,).Result()
if err1!=nil {
fmt.Println(err1)
return
}
for inx, item := range mapOut {
fmt.Printf("\n %s:%s", inx, item)
}
}
Hash 操作
func HashDemo() {
fmt.Println("-----------------------welcome to HashDemo-----------------------")
redisClient := GetRedisClient()
if redisClient == nil {
fmt.Errorf("HashDemo redisClient is nil")
return
}
article := Article{, "测试文章内容22222", "测试文章内容22222测试文章内容22222测试文章内容22222", , }
articleKey := "article:18"
redisClient.HMSet(articleKey, ToStringDictionary(&article))
mapOut := redisClient.HGetAll(articleKey).Val()
for inx, item := range mapOut {
fmt.Printf("\n %s:%s", inx, item)
}
fmt.Print("\n")
redisClient.HSet(articleKey, "Content", "测试文章内容")
mapOut = redisClient.HGetAll(articleKey).Val()
for inx, item := range mapOut {
fmt.Printf("\n %s:%s", inx, item)
}
fmt.Print("\n")
view, err := redisClient.HIncrBy(articleKey, "Views", ).Result()
if err != nil {
fmt.Printf("\n HIncrBy error=%s ", err)
} else {
fmt.Printf("\n HIncrBy Views=%d ", view)
}
fmt.Print("\n")
mapOut = redisClient.HGetAll(articleKey).Val()
for inx, item := range mapOut {
fmt.Printf("\n %s:%s", inx, item)
}
fmt.Print("\n")
}
连接池
func GetRedisClientPool() *Client{
redisdb := NewClient(&Options{
Addr: "127.0.0.1:6379",
Password: "",
DB: ,
PoolSize: ,})
pong, err := redisdb.Ping().Result()
if err != nil {
fmt.Println(pong, err)
}
return redisdb
}
// 连接池测试
func connectPoolTest() {
fmt.Println("-----------------------welcome to connect Pool Test-----------------------")
client :=GetRedisClientPool()
wg := sync.WaitGroup{}
wg.Add() for i := ; i < ; i++ {
go func() {
defer wg.Done() for j := ; j < ; j++ {
client.Set(fmt.Sprintf("name%d", j), fmt.Sprintf("xys%d", j), ).Err()
client.Get(fmt.Sprintf("name%d", j)).Result()
} fmt.Printf("PoolStats, TotalConns: %d, IdleConns: %d\n", client.PoolStats().TotalConns, client.PoolStats().IdleConns);
}()
} wg.Wait()
}
完整代码
package main import (
"fmt"
. "github.com/go-redis/redis"
. "redisDemo/models"
"time"
"sync"
) func main() {
fmt.Println("-----------------------welcome to redisdemo-----------------------")
//StringDemo()
//ListDemo()
//HashDemo()
connectPoolTest()
} func StringDemo() {
fmt.Println("-----------------------welcome to StringDemo-----------------------")
redisClient:=GetRedisClient()
if redisClient ==nil{
fmt.Errorf("StringDemo redisClient is nil")
return
} name := "张三"
key :="name:zhangsan"
redisClient.Set(key , name, * time.Second)
val := redisClient.Get(key)
if val == nil {
fmt.Errorf("StringDemo get error")
}
fmt.Println("name", val)
} func ListDemo(){
fmt.Println("-----------------------welcome to ListDemo-----------------------")
redisClient:=GetRedisClient()
if redisClient == nil {
fmt.Errorf("ListDemo redisClient is nil")
return
}
articleKey := "article"
result,err:=redisClient.RPush(articleKey, "a","b","c").Result() //在名称为 key 的list尾添加一个值为value的元素
if err!=nil {
fmt.Println(err)
return
}
fmt.Println("result:",result) result,err = redisClient.LPush(articleKey, "d").Result() //在名称为 key 的list头添加一个值为value的元素
if err!=nil {
fmt.Println(err)
return
}
fmt.Println("result:",result) length, err := redisClient.LLen(articleKey).Result()
if err != nil {
fmt.Println("ListDemo LLen is nil")
}
fmt.Println("length: ", length) // 长度 mapOut,err1:=redisClient.LRange(articleKey,,).Result()
if err1!=nil {
fmt.Println(err1)
return
}
for inx, item := range mapOut {
fmt.Printf("\n %s:%s", inx, item)
}
} func HashDemo() {
fmt.Println("-----------------------welcome to HashDemo-----------------------")
redisClient := GetRedisClient()
if redisClient == nil {
fmt.Errorf("HashDemo redisClient is nil")
return
}
article := Article{, "测试文章内容22222", "测试文章内容22222测试文章内容22222测试文章内容22222", , }
articleKey := "article:18" redisClient.HMSet(articleKey, ToStringDictionary(&article))
mapOut := redisClient.HGetAll(articleKey).Val()
for inx, item := range mapOut {
fmt.Printf("\n %s:%s", inx, item)
}
fmt.Print("\n") redisClient.HSet(articleKey, "Content", "测试文章内容")
mapOut = redisClient.HGetAll(articleKey).Val()
for inx, item := range mapOut {
fmt.Printf("\n %s:%s", inx, item)
}
fmt.Print("\n") view, err := redisClient.HIncrBy(articleKey, "Views", ).Result()
if err != nil {
fmt.Printf("\n HIncrBy error=%s ", err)
} else {
fmt.Printf("\n HIncrBy Views=%d ", view)
}
fmt.Print("\n") mapOut = redisClient.HGetAll(articleKey).Val()
for inx, item := range mapOut {
fmt.Printf("\n %s:%s", inx, item)
}
fmt.Print("\n") } func GetRedisClient() *Client {
redisdb := NewClient(&Options{
Addr: "127.0.0.1:6379",
Password: "", // no password set
DB: , // use default DB
}) pong, err := redisdb.Ping().Result()
if err != nil {
fmt.Println(pong, err)
}
return redisdb
} func GetRedisClientPool() *Client{
redisdb := NewClient(&Options{
Addr: "127.0.0.1:6379",
Password: "",
DB: ,
PoolSize: ,}) pong, err := redisdb.Ping().Result()
if err != nil {
fmt.Println(pong, err)
}
return redisdb
} // 连接池测试
func connectPoolTest() {
fmt.Println("-----------------------welcome to connect Pool Test-----------------------")
client :=GetRedisClientPool()
wg := sync.WaitGroup{}
wg.Add() for i := ; i < ; i++ {
go func() {
defer wg.Done() for j := ; j < ; j++ {
client.Set(fmt.Sprintf("name%d", j), fmt.Sprintf("xys%d", j), ).Err()
client.Get(fmt.Sprintf("name%d", j)).Result()
} fmt.Printf("PoolStats, TotalConns: %d, IdleConns: %d\n", client.PoolStats().TotalConns, client.PoolStats().IdleConns);
}()
} wg.Wait()
}
最后
1. go语言使用Redis 还是非常简单的,以上已经把Redis 的基本的用法讲完了。大家可以自己动手写代码试试。
2. 完整代码:点击下载
Golang 入门系列(七) Redis的使用的更多相关文章
- Golang 入门系列(十一)Go语言实现webapi
之前,已经讲过很多Golang的东西,比如基础语法,mysql的使用,redis的使用等等,感兴趣的可以看看以前的文章,https://www.cnblogs.com/zhangweizhong/ca ...
- Golang 入门系列(十三)用Beego开发web应用
接着之前的内容,前面已经讲过很多Golang的基础语法,mysql的使用,redis的使用,也讲了orm框架,如何创建一个webapi 服务等等,感兴趣的可以看看以前的文章,https://www.c ...
- Golang 入门系列(十五)如何理解go的并发?
前面已经讲过很多Golang系列知识,感兴趣的可以看看以前的文章,https://www.cnblogs.com/zhangweizhong/category/1275863.html, 接下来要说的 ...
- Golang 入门系列(十六)锁的使用场景主要涉及到哪些?读写锁为什么会比普通锁快
前面已经讲过很多Golang系列知识,感兴趣的可以看看以前的文章,https://www.cnblogs.com/zhangweizhong/category/1275863.html, 接下来要说的 ...
- Golang 入门系列(十七)几个常见的并发模型——生产者消费者模型
前面已经讲过很多Golang系列知识,包括并发,锁等内容,感兴趣的可以看看以前的文章,https://www.cnblogs.com/zhangweizhong/category/1275863.ht ...
- Golang 入门系列(十) mysql数据库的使用
之前,已经讲过一些Golang的基础的东西,感兴趣的可以看看以前的文章,https://www.cnblogs.com/zhangweizhong/category/1275863.html, 今天简 ...
- Golang 入门系列(九) 如何读取YAML,JSON,INI等配置文件
实际项目中,读取相关的系统配置文件是很常见的事情.今天就来说一说,Golang 是如何读取YAML,JSON,INI等配置文件的. 1. json使用 JSON 应该比较熟悉,它是一种轻量级的数据交换 ...
- Golang 入门系列(八) cron定时任务
1.cron 表达式的基本格式 Go 实现的cron 表达式的基本语法跟linux 中的 crontab基本是类似的.cron(计划任务),就是按照约定的时间,定时的执行特定的任务(job).cro ...
- Golang 入门系列(五)GO语言中的面向对象
前面讲了很多Go 语言的基础知识,包括go环境的安装,go语言的语法等,感兴趣的朋友可以先看看之前的文章.https://www.cnblogs.com/zhangweizhong/category/ ...
随机推荐
- RDIFramework.NET ━ .NET快速信息化系统开发框架 V3.2->WinForm版本新增新的角色授权管理界面效率更高、更规范
角色授权管理模块主要是对角色的相应权限进行集中设置.在角色权限管理模块中,管理员可以添加或移除指定角色所包含的用户.可以分配或授予指定角色的模块(菜单)的访问权限.可以收回或分配指定角色的操作(功能) ...
- BootStrap之 提示工具(Tooltip)插件
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title> ...
- asp.net mvc Html.BeginForm()及Html.Action用法
Html.BeginForm Add:操作方法的名称,Activities:控制器的名称,FormMethod.Post:定义from的method的值,,new { id = "fo ...
- WPF DesiredSize & RenderSize
DesiredSize DesiredSize介绍 关于DesiredSize的介绍,可以查看最新微软文档对DesiredSize的介绍 DesiredSize,指的是元素在布局过程中计算所需要的大小 ...
- [MySQL] timestamp和datetime的区别和大坑
1.timestamp占用4个字节;datetime占用8个字节2.timestamp范围1970-01-01 00:00:01.000000 到 2038-01-19 03:14:07.999999 ...
- 学JAVA第三天,JAVA第二章《JAVA数据类型》
---恢复内容开始--- <JAVA数据类型> 我们一般都用int类型,因为int类行一般的日常生活的数据都能满足了. 当然,想李嘉诚,马云这种有钱人,int类行就不能满足帮他记钱的了,像 ...
- 2018.12/17 function 的闭包
1.闭包:函数在调用的时候会形成一个私有的作用域,对内部变量起到保护的作用,这就是闭包. 2.变量销毁: 1.人为销毁 var a=12; a=null 2.自然销毁 函数调用完成之后 浏览器会自 ...
- Linux系统使用
linux(操作系统的内核) 浏览器功能:(内核的解释) 各个浏览器 实现的方式不一样 呈现内容 //解析内容和样式 用—webkit— (内核)解析 实现交互逻辑 v8 引擎 (内核) 实现 =&g ...
- 【20190407】JavaScript-indexOf方法解析
在JavaScript中,字符串类型String和数组类型Array都有indexOf()方法,虽然他们的作用都是返回传入元素在指定字符串或数组中的位置,但他们之间还是存在着一点点不同. Str.in ...
- Android为TV端助力 UDP协议
废话不多说.直接上代码! 一. 接收端 1.创建UDP连接 public void init() { try { //开关的作用 isRunning = true; DatagramSocket mU ...