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/ ...
随机推荐
- JDK源码分析(7)之 Reference 框架概览
对于Reference类大家可能会比较陌生,平时用的也比较少,对他的印象可能仅停在面试的时候查看引用相关的知识点:但在仔细查看源码后发现Reference还是非常实用的,平时我们使用的类都是强引用的, ...
- Linux 文件权限于目录配置
用户与用户组 我們以王三毛為例,王三毛這個『檔案』的擁有者為王三毛,他屬於王大毛這個群組, 而張小豬相對於王三毛,則只是一個『其他人(others)』而已. 不過,這裡有個特殊的人物要來介紹的,那就是 ...
- React事件杂记及源码分析
前提 最近通过阅读React官方文档的事件模块,发现了其主要提到了以下三个点 调用方法时需要手动绑定this React事件是一种合成事件SyntheticEvent,什么是合成事件? 事件属性 ...
- js中获取URL参数的共通方法getRequest()方法
getRequest : function() { var url = location.search; //获取url中"?"符后的字串 var theRequest = new ...
- 关于token和refresh token
最近在做公司的认证系统,总结了如下一番心得. 传统的认证方式一般采用cookie/session来实现,这是我们的出发点. 1.为什么选用token而不选用cookie/session? 本质上tok ...
- CSS像素、物理像素、逻辑像素、设备像素比、PPI、Viewport
1.PX(CSS pixels) 1.1 定义 虚拟像素,可以理解为“直觉”像素,CSS和JS使用的抽象单位,浏览器内的一切长度都是以CSS像素为单位的,CSS像素的单位是px. 1.2 注意 在CS ...
- Mysql表分区的选择与实践小结
在一些系统中有时某张表会出现百万或者千万的数据量,尽管其中使用了索引,查询速度也不一定会很快.这时候可能就需要通过分库,分表,分区来解决这些性能瓶颈. 一. 选择合适的解决方法 1. 分库分表. 分库 ...
- CSS变量(自定义属性)实践指南
本文翻译自:https://www.sitepoint.com/practical-guide-css-variables-custom-properties/ 转载请注明出处:葡萄城官网,葡萄城为开 ...
- iOS-----------关于UDID
最近看友盟的SDK更新日志:(设备系统的正常升级不会改变OpenUDID) Apple公司于2013年5月1日开始,拒绝采集UDID的App上架App Store. 为适应Apple公司的这一政策,2 ...
- java设计模式——适配器模式 Java源代码
前言:适配器模式就是把一个类的接口变换成客户端所能接受的另一种接口,从而使两个接口不匹配而无法在一起工作的两个类能够在一起工作.通常被用在一个项目需要引用一些开源框架来一起工作时,这些框架的内部都有一 ...