本文主要介紹redis安裝和使用。首先安裝redis依賴庫,這里是v8版本;然后連接redis,完成基本配置;最后測試封裝的工具類
歡迎大家訪問個人博客網(wǎng)址:https://www.maogeshuo.com,博主努力更新中…
參考文件:
- Yaml文件配置,Config使用
- Log日志封裝
- 常用工具類封裝
安裝redis依賴庫
命令行安裝redis
go get github.com/go-redis/redis/v8
連接redis和配置
首先創(chuàng)建了一個 Redis 客戶端,并連接到本地 Redis 服務(wù)器(默認(rèn)端口為 6379)。連接完成后,使用Ping函數(shù)測試連接是否成功。文章來源:http://www.zghlxwxcb.cn/news/detail-838801.html
package core
import (
"context"
"fmt"
"github.com/go-redis/redis/v8"
"time"
)
// https://zhuanlan.zhihu.com/p/637537337
// https://blog.csdn.net/qq_44237719/article/details/128920821
var Redis *RedisClient
type RedisClient struct {
client *redis.Client
ctx context.Context
}
// InitRedis 初始化redis
func InitRedis() {
redisConfig := Config.Redis
client := redis.NewClient(&redis.Options{
Addr: fmt.Sprintf("%s:%d", redisConfig.Host, redisConfig.Port),
Password: redisConfig.Password,
DB: redisConfig.Db,
})
redisClient := &RedisClient{
client: client,
ctx: context.Background(),
}
Redis = redisClient
_, err := client.Ping(client.Context()).Result()
if err != nil {
LOG.Println("redis連接失?。?)
return
}
LOG.Println("redis連接成功!")
}
工具類封裝
/*------------------------------------ 字符 操作 ------------------------------------*/
// Set 設(shè)置 key的值
func (this *RedisClient) Set(key, value string) bool {
result, err := this.client.Set(this.ctx, key, value, 0).Result()
if err != nil {
LOG.Println(err)
return false
}
return result == "OK"
}
// SetEX 設(shè)置 key的值并指定過期時間
func (this *RedisClient) SetEX(key, value string, ex time.Duration) bool {
result, err := this.client.Set(this.ctx, key, value, ex).Result()
if err != nil {
LOG.Println(err)
return false
}
return result == "OK"
}
// Get 獲取 key的值
func (this *RedisClient) Get(key string) (bool, string) {
result, err := this.client.Get(this.ctx, key).Result()
if err != nil {
LOG.Println(err)
return false, ""
}
return true, result
}
// GetSet 設(shè)置新值獲取舊值
func (this *RedisClient) GetSet(key, value string) (bool, string) {
oldValue, err := this.client.GetSet(this.ctx, key, value).Result()
if err != nil {
LOG.Println(err)
return false, ""
}
return true, oldValue
}
// Incr key值每次加一 并返回新值
func (this *RedisClient) Incr(key string) int64 {
val, err := this.client.Incr(this.ctx, key).Result()
if err != nil {
LOG.Println(err)
}
return val
}
// IncrBy key值每次加指定數(shù)值 并返回新值
func (this *RedisClient) IncrBy(key string, incr int64) int64 {
val, err := this.client.IncrBy(this.ctx, key, incr).Result()
if err != nil {
LOG.Println(err)
}
return val
}
// IncrByFloat key值每次加指定浮點型數(shù)值 并返回新值
func (this *RedisClient) IncrByFloat(key string, incrFloat float64) float64 {
val, err := this.client.IncrByFloat(this.ctx, key, incrFloat).Result()
if err != nil {
LOG.Println(err)
}
return val
}
// Decr key值每次遞減 1 并返回新值
func (this *RedisClient) Decr(key string) int64 {
val, err := this.client.Decr(this.ctx, key).Result()
if err != nil {
LOG.Println(err)
}
return val
}
// DecrBy key值每次遞減指定數(shù)值 并返回新值
func (this *RedisClient) DecrBy(key string, incr int64) int64 {
val, err := this.client.DecrBy(this.ctx, key, incr).Result()
if err != nil {
LOG.Println(err)
}
return val
}
// Del 刪除 key
func (this *RedisClient) Del(key string) bool {
result, err := this.client.Del(this.ctx, key).Result()
if err != nil {
return false
}
return result == 1
}
// Expire 設(shè)置 key的過期時間
func (this *RedisClient) Expire(key string, ex time.Duration) bool {
result, err := this.client.Expire(this.ctx, key, ex).Result()
if err != nil {
return false
}
return result
}
/*------------------------------------ list 操作 ------------------------------------*/
// LPush 從列表左邊插入數(shù)據(jù),并返回列表長度
func (this *RedisClient) LPush(key string, date ...interface{}) int64 {
result, err := this.client.LPush(this.ctx, key, date).Result()
if err != nil {
LOG.Println(err)
}
return result
}
// RPush 從列表右邊插入數(shù)據(jù),并返回列表長度
func (this *RedisClient) RPush(key string, date ...interface{}) int64 {
result, err := this.client.RPush(this.ctx, key, date).Result()
if err != nil {
LOG.Println(err)
}
return result
}
// LPop 從列表左邊刪除第一個數(shù)據(jù),并返回刪除的數(shù)據(jù)
func (this *RedisClient) LPop(key string) (bool, string) {
val, err := this.client.LPop(this.ctx, key).Result()
if err != nil {
LOG.Println(err)
return false, ""
}
return true, val
}
// RPop 從列表右邊刪除第一個數(shù)據(jù),并返回刪除的數(shù)據(jù)
func (this *RedisClient) RPop(key string) (bool, string) {
val, err := this.client.RPop(this.ctx, key).Result()
if err != nil {
fmt.Println(err)
return false, ""
}
return true, val
}
// LIndex 根據(jù)索引坐標(biāo),查詢列表中的數(shù)據(jù)
func (this *RedisClient) LIndex(key string, index int64) (bool, string) {
val, err := this.client.LIndex(this.ctx, key, index).Result()
if err != nil {
LOG.Println(err)
return false, ""
}
return true, val
}
// LLen 返回列表長度
func (this *RedisClient) LLen(key string) int64 {
val, err := this.client.LLen(this.ctx, key).Result()
if err != nil {
LOG.Println(err)
}
return val
}
// LRange 返回列表的一個范圍內(nèi)的數(shù)據(jù),也可以返回全部數(shù)據(jù)
func (this *RedisClient) LRange(key string, start, stop int64) []string {
vales, err := this.client.LRange(this.ctx, key, start, stop).Result()
if err != nil {
LOG.Println(err)
}
return vales
}
// LRem 從列表左邊開始,刪除元素data, 如果出現(xiàn)重復(fù)元素,僅刪除 count次
func (this *RedisClient) LRem(key string, count int64, data interface{}) bool {
_, err := this.client.LRem(this.ctx, key, count, data).Result()
if err != nil {
fmt.Println(err)
}
return true
}
// LInsert 在列表中 pivot 元素的后面插入 data
func (this *RedisClient) LInsert(key string, pivot int64, data interface{}) bool {
err := this.client.LInsert(this.ctx, key, "after", pivot, data).Err()
if err != nil {
LOG.Println(err)
return false
}
return true
}
/*------------------------------------ set 操作 ------------------------------------*/
// SAdd 添加元素到集合中
func (this *RedisClient) SAdd(key string, data ...interface{}) bool {
err := this.client.SAdd(this.ctx, key, data).Err()
if err != nil {
LOG.Println(err)
return false
}
return true
}
// SCard 獲取集合元素個數(shù)
func (this *RedisClient) SCard(key string) int64 {
size, err := this.client.SCard(this.ctx, "key").Result()
if err != nil {
LOG.Println(err)
}
return size
}
// SIsMember 判斷元素是否在集合中
func (this *RedisClient) SIsMember(key string, data interface{}) bool {
ok, err := this.client.SIsMember(this.ctx, key, data).Result()
if err != nil {
LOG.Println(err)
}
return ok
}
// SMembers 獲取集合所有元素
func (this *RedisClient) SMembers(key string) []string {
es, err := this.client.SMembers(this.ctx, key).Result()
if err != nil {
LOG.Println(err)
}
return es
}
// SRem 刪除 key集合中的 data元素
func (this *RedisClient) SRem(key string, data ...interface{}) bool {
_, err := this.client.SRem(this.ctx, key, data).Result()
if err != nil {
LOG.Println(err)
return false
}
return true
}
// SPopN 隨機返回集合中的 count個元素,并且刪除這些元素
func (this *RedisClient) SPopN(key string, count int64) []string {
vales, err := this.client.SPopN(this.ctx, key, count).Result()
if err != nil {
LOG.Println(err)
}
return vales
}
/*------------------------------------ hash 操作 ------------------------------------*/
// HSet 根據(jù) key和 field字段設(shè)置,field字段的值
func (this *RedisClient) HSet(key, field, value string) bool {
err := this.client.HSet(this.ctx, key, field, value).Err()
if err != nil {
return false
}
return true
}
// HGet 根據(jù) key和 field字段,查詢field字段的值
func (this *RedisClient) HGet(key, field string) string {
val, err := this.client.HGet(this.ctx, key, field).Result()
if err != nil {
LOG.Println(err)
}
return val
}
// HMGet 根據(jù)key和多個字段名,批量查詢多個 hash字段值
func (this *RedisClient) HMGet(key string, fields ...string) []interface{} {
vales, err := this.client.HMGet(this.ctx, key, fields...).Result()
if err != nil {
panic(err)
}
return vales
}
// HGetAll 根據(jù) key查詢所有字段和值
func (this *RedisClient) HGetAll(key string) map[string]string {
data, err := this.client.HGetAll(this.ctx, key).Result()
if err != nil {
LOG.Println(err)
}
return data
}
// HKeys 根據(jù) key返回所有字段名
func (this *RedisClient) HKeys(key string) []string {
fields, err := this.client.HKeys(this.ctx, key).Result()
if err != nil {
LOG.Println(err)
}
return fields
}
// HLen 根據(jù) key,查詢hash的字段數(shù)量
func (this *RedisClient) HLen(key string) int64 {
size, err := this.client.HLen(this.ctx, key).Result()
if err != nil {
LOG.Println(err)
}
return size
}
// HMSet 根據(jù) key和多個字段名和字段值,批量設(shè)置 hash字段值
func (this *RedisClient) HMSet(key string, data map[string]interface{}) bool {
result, err := this.client.HMSet(this.ctx, key, data).Result()
if err != nil {
LOG.Println(err)
return false
}
return result
}
// HSetNX 如果 field字段不存在,則設(shè)置 hash字段值
func (this *RedisClient) HSetNX(key, field string, value interface{}) bool {
result, err := this.client.HSetNX(this.ctx, key, field, value).Result()
if err != nil {
LOG.Println(err)
return false
}
return result
}
// HDel 根據(jù) key和字段名,刪除 hash字段,支持批量刪除
func (this *RedisClient) HDel(key string, fields ...string) bool {
_, err := this.client.HDel(this.ctx, key, fields...).Result()
if err != nil {
LOG.Println(err)
return false
}
return true
}
// HExists 檢測 hash字段名是否存在
func (this *RedisClient) HExists(key, field string) bool {
result, err := this.client.HExists(this.ctx, key, field).Result()
if err != nil {
LOG.Println(err)
return false
}
return result
}
代碼測試
func TestRedis() {
core.Redis.Set("test", "value1")
if ok, s := core.Redis.Get("test"); ok {
core.LOG.Println("test: ", s)
}
core.Redis.SetEX("test2", "value2", 10*time.Minute)
if okEx, sEx := core.Redis.Get("test2"); okEx {
core.LOG.Println("test2: ", sEx)
}
}
文章來源地址http://www.zghlxwxcb.cn/news/detail-838801.html
到了這里,關(guān)于【go語言開發(fā)】redis簡單使用的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!