一扑眉、redis連接
引入包"github.com/go-redis/redis/v8"
var(
redisInstance *redis.Client
)
func init() {
redisI :=redis.NewClient(&redis.Options{
Addr:“http://192.168.90.86:6379”,
? ? ? Password:"123456", // 設(shè)置密碼
? ? ? DB:0,? // use default DB
? })
redisInstance = redisI
}
func GetRedis() *redis.Client{
? ? ?return redisInstance
}
二鹿寻、redis,string類型存取
var ctx = context.TODO()
/**
* 判斷key是否存在
*/
func RedisExists(keystring) (bool,error) {
????client :=conn.GetRedis()
????if client !=nil{
????????r,err := client.Exists(ctx,key).Result()
? ? ? ?if err ==nil {
????????????if r ==1 {
????????????????????return true, nil
? ? ? ? ? ? }else{
????????????????return false, nil
? ? ? ? ???? }
????????}
}
????return false, errors.New("查詢key失敗")
}
/**
* redis設(shè)置值
*/
func SetRedisCache(keystring,valueinterface{},durationtime.Duration)error {
client :=conn.GetRedis()
if client !=nil{
_,err := client.Set(ctx,key,value,duration).Result()
return err
}else{
return errors.New("redis連接失敗")
}
}
/**
* redis獲取值
*/
func GetRedisCache(keystring) (interface{},error) {
client :=conn.GetRedis()
if client !=nil{
????r,err := client.Get(ctx,key).Result()
????if err ==redis.Nil {
????????return nil,nil
? ? ? }else if err !=nil {
????????return nil,err
? ? ? ?}else {
????????????return r,nil
? ? ? }
? ? }else{
????????????return nil,errors.New("redis連接失敗")
????}
}
/**
* 移除
*/
func ClearRedisCache(keystring)? {
????????client :=conn.GetRedis()
????????if client !=nil{
????????????client.Move(ctx,key,0)
????????}????
}
三抹估、docker啟動(dòng)redis
拉取鏡像
docker pull redis:latest
//docker啟動(dòng)redis鏡像
docker run --name my_redis -p 6379:6379 -d --restart=always redis:latest redis-server --appendonly yes --requirepass "123456"
//測(cè)試
redis-cli -h 192.168.90.86 -p 6379
10.249.91.86:6379> set text1 2
(error) NOAUTH Authentication required.
192.168.90.86:6379> auth 123456
OK
192.168.90.86:6379> set text1 2
OK
192.168.90.86:6379> keys *
1) "text1"
2) "text"
10.249.91.86:6379>?