Golang Redis database connection

GolangConnection Redisdatabase


golangConnect to the database, where bloggers recommend using go-redisthis library, the reason is very simple (similar to the operation of the database connection input command in a database)

go-redisInstallation

go get -v https://github.com/go-redis/redis

-vSmall v, is the output process. Under normal circumstances without -vany feedback I could not see.


Connection redisway

package ...

import (
 "github.com/go-redis/redis"
)

func main() {
 client := redis.NewClient(&redis.Options{
     Addr:		"127.0.0.1:6379",
     Password:	"",
     DB:			0,
 })
 defer client.Close()   
}

Incidentally, redisyou can set the number of banks is 255one, but in fact we are connected using only 0-19twenty libraries. Under the default configuration, redisyou can use 0-16the library


Share some use, very fast techniques

If you are using redis, you need to inquire about keythe existence of
value, _ := client.Exists(key).Result()

Return 1 or 0, 1 for key exists, 0 does not exist.


New key-valuekey-value pairs, you can use Setthe way

Here, we need to valuestring conversion

import (
	"encoding/json"
)

var value map[string]string{"username": "", "userpassword": ""}

mjson, _ := json.Marshal(value)
mString := string(mjson)

client.Set(UserName, mString, 0).Err()

Get key-value pairs, you can use Getthe way
UserInfo, _ := client.Get(UserName).Result()

UserNameIs the value you want to query, if you feel you do not know the value of the query is not, it is best to Existslook at

Returns Keythe corresponding Value, is stored value.


According to find a single condition, with the Keysway
keys, _ := client.Keys(search).Result()

Note, redisdoes not support multi-criteria search. That is the normal SQLsentence is not enough, after all, non-relational database Well ~

If you want more conditions, you can *key1*key2*write, but there are limitations.

If matched, it returns with keythe array. If there is no match to it returns an empty array.


More use, you can go from go-redisthe document point of view.

https://godoc.org/github.com/go-redis/redis
Published 99 original articles · won praise 34 · views 60000 +

Guess you like

Origin blog.csdn.net/qq_42346414/article/details/104881103