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/ ...
随机推荐
- 小程序开发笔记【一】,查询用户参与活动列表 left join on的用法
今天在做一个用户活动查询功能的时候,查询参与的活动.正常,使用egg-mysql查询数据一般会这么写 result = await this.app.mysql.select('tb_activity ...
- #7 Python代码调试
前言 Python已经学了这么久了,你现在已经长大了,该学会自己调试代码了!相信大家在编写程序过程中会遇到大量的错误信息,我也不例外的啦-遇到这些问题该怎么解决呢?使用最多的方法就是使用print打印 ...
- 菜鸟学ASP.NET MVC4入门笔记
ASP.NET MVC 是微软官方提供的以MVC模式为基础的ASP.NET Web应用程序(Web Application)框架,它由Castle的MonoRail而来. MVC 编程模式 MVC 是 ...
- ASP.NET Core介绍
认识ASP.NET Core ASP.NET Core是一个跨平台,高性能,开源的框架,用于构建现代,基于云的网络应用程序,使用ASP.NET Core可以实现: 开发web应用,服务,IoT应用和移 ...
- Python全栈开发之---mysql数据库
1.数据库的安装和连接 #数据库安装 pip install PyMySQL #数据库操作 import pymysql db = pymysql.connect("数据库ip", ...
- Vue UI:Vue开发者必不可少的工具
译者按: Vue开发工具越来越好用了! 原文: Vue UI: A First Look 译者: Fundebug 本文采用意译,版权归原作者所有 随着最新的稳定版本Vue CLI 3即将发布,是时候 ...
- HTML5利用canvas,把多张图合并成一张图片
需求分析,根据当前网页中的几张图片,在手机上长按,保存图片到相册或者发送给好友. drawCanvas(){ var self = this; var imgsrcArray = [ require( ...
- JS的MD5加密
/* * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message * Digest Algorithm, as d ...
- Github:failed to add file / to index
我把Test项目上传到github上,为了截一部分图,来写博客.所以我就上传成功之后,把仓库Respository Test删除了,但是当我再次上传的时候,发现上传不上,会提示failed to ad ...
- Android细笔记--DataStorage
Shared Preferences 即使应用被杀了,shared preference也还是存在的 Internal Storage 创建于internal的文件只对本应用开放权限,即使手机用户本身 ...