Golang
Connection Redis
database
golang
Connect to the database, where bloggers recommend usinggo-redis
this library, the reason is very simple (similar to the operation of the database connection input command in a database)
go-redis
Installationgo get -v https://github.com/go-redis/redis
-v
Small v, is the output process. Under normal circumstances without-v
any feedback I could not see.
Connection
redis
waypackage ... 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,
redis
you can set the number of banks is255
one, but in fact we are connected using only0-19
twenty libraries. Under the default configuration,redis
you can use0-16
the library
Share some use, very fast techniques
If you are using
redis
, you need to inquire aboutkey
the existence ofvalue, _ := client.Exists(key).Result()
Return 1 or 0, 1 for key exists, 0 does not exist.
New
key-value
key-value pairs, you can useSet
the wayHere, we need to
value
string conversionimport ( "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
Get
the wayUserInfo, _ := client.Get(UserName).Result()
UserName
Is the value you want to query, if you feel you do not know the value of the query is not, it is best toExists
look atReturns
Key
the correspondingValue
, is storedvalue
.
According to find a single condition, with the
Keys
waykeys, _ := client.Keys(search).Result()
Note,
redis
does not support multi-criteria search. That is the normalSQL
sentence 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
key
the array. If there is no match to it returns an empty array.
More use, you can go from
go-redis
the document point of view.https://godoc.org/github.com/go-redis/redis