国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

【go語言開發(fā)】redis簡單使用

這篇具有很好參考價值的文章主要介紹了【go語言開發(fā)】redis簡單使用。希望對大家有所幫助。如果存在錯誤或未考慮完全的地方,請大家不吝賜教,您也可以點擊"舉報違法"按鈕提交疑問。

本文主要介紹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ù)測試連接是否成功。

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)
	}
}

【go語言開發(fā)】redis簡單使用,go,golang,redis,bootstrap文章來源地址http://www.zghlxwxcb.cn/news/detail-838801.html

到了這里,關(guān)于【go語言開發(fā)】redis簡單使用的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實不符,請點擊違法舉報進行投訴反饋,一經(jīng)查實,立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費用

相關(guān)文章

  • 【Go語言開發(fā)】簡單了解一下搜索引擎并用go寫一個demo

    【Go語言開發(fā)】簡單了解一下搜索引擎并用go寫一個demo

    這篇文章我們一起來了解一下搜索引擎的原理,以及用go寫一個小demo來體驗一下搜索引擎。 搜索引擎一般簡化為三個步驟 爬蟲:爬取數(shù)據(jù)源,用做搜索數(shù)據(jù)支持。 索引:根據(jù)爬蟲爬取到的數(shù)據(jù)進行索引的建立。 排序:對搜索的結(jié)果進行排序。 然后我們再對幾個專業(yè)名詞做

    2024年02月16日
    瀏覽(26)
  • Go語言之 go-redis 基本使用

    Redis:https://redis.io/ Redis 中文網(wǎng):https://www.redis.net.cn/ REmote DIctionary Server(Redis) 是一個由Salvatore Sanfilippo寫的key-value存儲系統(tǒng)。 Redis是一個開源的使用ANSI C語言編寫、遵守BSD協(xié)議、支持網(wǎng)絡(luò)、可基于內(nèi)存亦可持久化的日志型、Key-Value數(shù)據(jù)庫,并提供多種語言的API。 它通常被稱為

    2024年02月09日
    瀏覽(25)
  • 一個golang小白使用vscode搭建Ununtu20.04下的go開發(fā)環(huán)境

    一個golang小白使用vscode搭建Ununtu20.04下的go開發(fā)環(huán)境

    先交代一下背景,距離正式接觸golang這門語言已經(jīng)有5年時間,平時偶爾也會用go寫寫工具和功能,但其實充其量就是語言小白,基本上就是按照教程配置好環(huán)境,按照需求寫寫邏輯,能跑起來就行了。golang隨著這幾年的變化,這門語言的變化還是非常大的,之前寫過一篇《

    2024年01月22日
    瀏覽(21)
  • Go語言之反射(反射的簡單使用,原理)

    Go語言之反射(反射的簡單使用,原理)

    1.什么是反射 Go語言中,反射的機制就是在運行的時候,可以獲取到其變量的類型和值,且可以對其類型和值進行檢查,對其值進行修改。 即在不知道具體的類型的情況下,可以用反射機制來查看變量類型、更新變量的值。 Go中反射主要涉及到兩個概念:Type和Value。對所有的

    2023年04月25日
    瀏覽(26)
  • Go 語言之 zap 日志庫簡單使用

    log:https://pkg.go.dev/log log 包是一個簡單的日志包。 Package log implements a simple logging package. It defines a type, Logger, with methods for formatting output. It also has a predefined \\\'standard\\\' Logger accessible through helper functions Print[f|ln], Fatal[f|ln], and Panic[f|ln], which are easier to use than creating a Logger manually. Th

    2024年02月09日
    瀏覽(28)
  • 【設(shè)計模式】使用 go 語言實現(xiàn)簡單工廠模式

    最近在看《大話設(shè)計模式》,這本書通過對話形式講解設(shè)計模式的使用場景,有興趣的可以去看一下。 第一篇講的是 簡單工廠模式 ,要求輸入兩個數(shù)和運算符號,得到運行結(jié)果。 這個需求不難,難就難在類要怎么設(shè)計,才能達到可復(fù)用、維護性強、可拓展和靈活性高。 運

    2024年02月05日
    瀏覽(31)
  • 使用Go語言編寫簡單的HTTP服務(wù)器

    使用Go語言編寫簡單的HTTP服務(wù)器

    在Go語言中,我們可以使用標(biāo)準(zhǔn)庫中的\\\"net/http\\\"包來編寫HTTP服務(wù)器。下面是一個簡單的示例,展示了如何使用Go編寫一個基本的HTTP服務(wù)器。 go 復(fù)制代碼 package ?main import ?( \\\"fmt\\\" ? \\\"net/http\\\" ? ) func ? main () ?{ // 創(chuàng)建一個處理器函數(shù),處理所有對根路徑的請求 handler := func (w http.

    2024年01月24日
    瀏覽(35)
  • GO語言使用最簡單的UI方案govcl

    GO語言使用最簡單的UI方案govcl

    接觸go語言有一兩年時間了。 之前用Qt和C#寫過桌面程序,C#會被別人扒皮,極度不爽;Qt默認(rèn)要帶一堆dll,或者靜態(tài)編譯要自己弄或者找?guī)?,有的庫還缺這缺那,很難編譯成功。 如果C# winform可以編譯成二進制原生exe的話,給人感覺是開發(fā)效率最好的。 C#有nuget可以用別人的庫

    2024年02月15日
    瀏覽(19)
  • golang redis第三方庫github.com/go-redis/redis/v8實踐

    這里示例使用 go-redis v8 ,不過 go-redis latest 是 v9 安裝v8:go get github.com/go-redis/redis/v8 Redis 5 種基本數(shù)據(jù)類型: ?string 字符串類型;list列表類型;hash哈希表類型;set集合類型;zset有序集合類型 ? 最基本的Set/Get操作 # setget.go package ?main import ?( \\\"context\\\" \\\"fmt\\\" \\\"time\\\" \\\"github.com/go-re

    2024年02月12日
    瀏覽(44)
  • Golang:Go語言結(jié)構(gòu)

    在我們開始學(xué)習(xí) Go 編程語言的基礎(chǔ)構(gòu)建模塊前,讓我們先來了解 Go 語言最簡單程序的結(jié)構(gòu)。 Go 語言的基礎(chǔ)組成有以下幾個部分: 包聲明 引入包 函數(shù) 變量 語句 表達式 注釋 接下來讓我們來看下簡單的代碼,該代碼輸出了\\\"Hello World!\\\": 讓我們來看下以上程序的各個部分: 第一

    2024年02月10日
    瀏覽(21)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包