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/ ...
随机推荐
- 【API知识】一种你可能没见过的Controller形式
前言 这里分享一下我遇到的一个挺有意思的Controller形式,内容涉及@RequestMapping注解的原理. 实际案例 一.基本描述 项目甲中有多个模块,其中就有模块A和B.(这里的模块指的是 ...
- Dockerfile 中的 COPY 与 ADD 命令
Dockerfile 中提供了两个非常相似的命令 COPY 和 ADD,本文尝试解释这两个命令的基本功能,以及其异同点,然后总结其各自适合的应用场景. Build 上下文的概念 在使用 docker ...
- 【Node.js】通过mongoose得到模型,不能新添字段的问题
问题描述 通过node.js为查询到的json对象添加新的字段,对象成功保存到数据库中,但新增字段却没保存. 前几天用vue+node.js+mongodb技术做一个购物车功能的网页,发现node.j ...
- 解读经典《C#高级编程》第七版 Page94-100.继承.Chapter4
前言 今天,我们开始进入第四章的解读.本章讲的是继承.要做稍微复杂一些的开发,便不可避免的会使用到继承.本篇文章我们主要解读"实现继承". 另外,从本文开始,我开始使用Markdo ...
- WCF和委托
WCF各个模块的联系: Contracts:一个类库项目,定义服务契约(Service Contract),引用System.ServiceMode程序集(WCF框架的绝大部分实现和API定 ...
- mysql报错:java.sql.SQLException: Incorrect string value: '\xE4\xB8\x80\xE6\xAC\xA1...' for column 'excelName' at row 1
一.问题 用Eclipse做项目时候报错 java.sql.SQLException: Incorrect string value: '\xE4\xB8\x80\xE6\xAC\xA1...' fo ...
- Dynamics 365执行操作报SQL Server已超时,更改这个超时设置的方法
本人微信公众号:微软动态CRM专家罗勇 ,回复291或者20190110可方便获取本文,同时可以在第一间得到我发布的最新博文信息,follow me!我的网站是 www.luoyong.me . 当执 ...
- CentOS6.9升级autoconf版本,解决”Autoconf version 2.64 or higher is required“错误
安装软件时提示说需要Autoconf 2.64或更高的版本: # autoconf configure.ac:: error: Autoconf version 2.64 or higher is r ...
- android中的相对路径
转载请标明出处:https://www.cnblogs.com/tangZH/p/9939655.html 1.同个文件夹访问 D:\Java\main\A.java D:\Java\main\B. ...
- log4j详细配置
参考博客:https://blog.csdn.net/sinat_30185177/article/details/73550377 log4j..很简单好用的一个记录日志的东东,正因为好用,本人从来 ...