golang redis高性能キャッシュとタイムアウト設定

44459 ワード

redisデータベースへのログイン
redis-cli -h 127.0.0.1 -p 6379 -a xxx (-a   )

redisバージョンの表示
redis-cli -v

redisのインストールに成功したことを確認
redis 127.0.0.1:6379>PING
PONG

初期化redis
方法1:
import (
    "github.com/go-redis/redis"
)

func main () {
	//           redis       ,    3s
	client := redis.NewClient(&redis.Options{
	        Addr:     "127.0.0.1:6379",
	        Password: "root",
	        DB:       0,
	    })
	    
	    //           
	    defer client.Close()
	    
	    //ping
	    pong, err := client.Ping().Result()
	    if err != nil {
	        fmt.Println("ping error", err.Error())
	        return
	    }
	    fmt.Println("ping result:", pong)
}

方式2:
import (
    "github.com/gomodule/redigo/redis"
    "time"
    "fmt"
)

type Redis struct {
    pool     *redis.Pool
}

var redis *Redis

//MaxIdle:            
//MaxActive:          
//IdleTimeout:     duration     ,    

//DialReadTimeout:  redis       
//DialWriteTimeout:  redis       
//DialConnectTimeout:  redis     
func initRedis() {
    redis = new(Redis)
    redis.pool = &redis.Pool{
        MaxIdle:     256,
        MaxActive:   0,
        IdleTimeout: time.Duration(120),
        Dial: func() (red.Conn, error) {
            return red.Dial(
                "tcp",
                "127.0.0.1:6379",
                redis.DialReadTimeout(time.Duration(1000)*time.Millisecond),
                redis.DialWriteTimeout(time.Duration(1000)*time.Millisecond),
                redis.DialConnectTimeout(time.Duration(1000)*time.Millisecond),
            )
        },
    }
}


redisロック
githubリンク:https://github.com/bsm/redislock
import (
  "fmt"
  "time"

  "github.com/bsm/redislock"
  "github.com/go-redis/redis/v7"
)

func main() {
	// Connect to redis.
	client := redis.NewClient(&redis.Options{
		Network:	"tcp",
		Addr:		"127.0.0.1:6379",
	})
	defer client.Close()

	// Create a new lock client.
	locker := redislock.New(client)

	// Try to obtain lock.
	// RetryCount     ,RetryBackoff       
	option := redislock.Options{
		RetryCount:   1,
		RetryBackoff: 100ms,
		Metadata:     "",
		Context:      nil,
	}
	// Obtain      key,            100s,       

	lock, err := locker.Obtain("key", 100*time.Second, option)
	if err == redislock.ErrNotObtained {
		fmt.Println("Could not obtain lock!")
	} else if err != nil {
		log.Fatalln(err)
	}

	// Don't forget to defer Release.
	defer lock.Release()
	fmt.Println("I have a lock!")

	// Sleep and check the remaining TTL.
	time.Sleep(50 * time.Second)
	if ttl, err := lock.TTL(); err != nil {
		log.Fatalln(err)
	} else if ttl > 0 {
		fmt.Println("Yay, I still have my lock!")
	}

	// Extend my lock.
	if err := lock.Refresh(100*time.Millisecond, nil); err != nil {
		log.Fatalln(err)
	}

	// Sleep a little longer, then check.
	time.Sleep(100 * time.Millisecond)
	if ttl, err := lock.TTL(); err != nil {
		log.Fatalln(err)
	} else if ttl == 0 {
		fmt.Println("Now, my lock has expired!")
	}

}


redisに格納されている5種類のデータ型
リファレンス接続:https://redis.readthedocs.io/en/2.4/sorted_set.html
1、String:文字列2、Hash:ハッシュ3、List:リスト4、Set:重複なし集合5、Sorted Set:順序付き重複なし集合(データはすべて優先順位付き)
//   key      [String、Hash、List、Set、Sorted Set]
keyType, err = p.client.Type(key).Result()

stringタイプ
redis 127.0.0.1:6379>SET amberStr "amber"
redis 127.0.0.1:6379>GET amberStr
"amber"

golang実装string
key := "amberStr"
err = client.Set(key, "amber", time.Hour).Err()  
value, err := client.Get(key).Result()

hashタイプ
redis 127.0.0.1:6379> HMSET amberHS one "Hello" two "World"
"OK"
redis 127.0.0.1:6379> HGET amberHS one
"Hello"
redis 127.0.0.1:6379> HGET amberHS two
"World"
redis 127.0.0.1:6379> DEL runoob

golang実現hash
key := "amberHASH"  
client.HSet(key, "name", "amber")  
client.HSet(key, "age", 18)  
  
//get hash  
hashGet, _ := client.HGet(key, "name").Result()  
fmt.Println("HGet name", hashGet)  
  
//    hash   map  
hashGetAll, _ := client.HGetAll(key).Result()  
fmt.Println("HGetAll", hashGetAll)

リストタイプ
redis 127.0.0.1:6379> rpush amberLS hello
(integer) 1
redis 127.0.0.1:6379> rpush amberLS world
(integer) 2
redis 127.0.0.1:6379> rpush amberLS !
(integer) 3
redis 127.0.0.1:6379> lrange amberLS 0 10
1) "hello"
2) "world"
3) "!"
redis 127.0.0.1:6379> DEL amberLS 

golang実装list
key := "amberLS"  
client.RPush(key, "hello", 10, "world", 15, "golang", 20).Err()  
  
//lpop               
first, _ := client.LPop(key).Result()  
  
//blpop             ,                              。  
first2, _ := client.BLPop(time.Second*60, key).Result()  
  
//      
listLen, _ := client.LLen(key).Result()  
fmt.Println("list length", listLen)  
  
//      
listGet, _ := client.LRange(key, 1, 2).Result()  
fmt.Println("  1-2 2     ", listGet)


setタイプ
#           
redis 127.0.0.1:6379>SADD amberSet "amber"

redis 127.0.0.1:6379>SMEMBERS amberSet

redis 127.0.0.1:6379> SETNX unique "one" 
(integer) 1

redis 127.0.0.1:6379> SETNX unique "two"  
(integer) 0

redis 127.0.0.1:6379> GET unique 
"one"

golang実装set
key := "amberSet"  
client.SAdd(key, "cat")  
client.SAdd(key, "dog")  
client.SAdd(key, "monkey")  
client.SAdd(key, ["rabbit", "tiger"])  

//     ,          ,      expire
_, err = client.SAdd(key, ["cat","dog"]).Result()

//           
setList, _ := client.SMembers(key).Result()  

//         
client.SRem(key, "cat")  
  
//     set         
setFirst, _ := client.SPop(key).Result() 

//          
setList, _ := client.SMembers(key).Result()

//     set       ,  set    
setFirst, _ := client.SPop(key).Result()

//          
count, _ := client.Scard(key).Result()  

//         ,         ,           ,         
count, _ := client.SRem(key,"dog").Result()

//    set  
client.Del(key).Result()

//         
client.Expire(key, time.Hour).Result()

//   
client.SetNX("key", "true", time.Second).Result()

ZSetタイプ
ここで優先順位は数値で、オブジェクトの前にあります.
redis 127.0.0.1:6379> zadd amberZSet 10 dog
(integer) 1
redis 127.0.0.1:6379> zadd amberZSet 20 kitty
(integer) 1
redis 127.0.0.1:6379> zadd amberZSet 30 monkey
(integer) 1
redis 127.0.0.1:6379> zadd amberZSet 30 monkey
(integer) 0
redis 127.0.0.1:6379> > ZRANGEBYSCORE amberZSet 0 1000
1) "dog"
2) "kitty"
3) "monkey"

golang実装zset
key := "amberSet"  
ranking := []*redis.Z{  
  &redis.Z{Score: 100.0, Member: "dog"},  
  &redis.Z{Score: 80.0, Member: "cat"},  
  &redis.Z{Score: 70.0, Member: "kitty"},  
  &redis.Z{Score: 75.0, Member: "monkey"},  
}  
client.ZAdd(zsetKey, ranking...)  

//cat+5   
newScore, err := client.ZIncrBy(key, 5.0, "cat").Result()  
fmt.Println(" 5       ", newScore)  

// zset   4      ,       
zset, _ := client.ZRevRangeWithScores(key, 0, 3).Result()  
fmt.Println("zset 4 ", zset)

//  pop     /   key value,redis5.0    
keyValue, _ := client.ZPopMax(key).Result()  
keyValue, _ := client.ZPopMin(key).Result()  

コード例SetNX
func setnx() error{
	if success, err := client.SetNX("one", "true", 0).Result(); err != nil {
		errInfo = fmt.Sprintf("fail to set one to redis with error: %v", err)
		return fmt.Errorf(errInfo)
	} else if !success {
		errInfo = fmt.Sprintf("one has been setnx by other")
		return nil
		}
}
//err      redis      
//success=false  key     
//SetNX     key,      value,      key              ,0