This is a creation in
Article, where the information may have evolved or changed.
-
- Using the Redis database in the Go language
- Connect to Redis
- Storing and retrieving data
- Decode into JSON
- Finally, you should use a connection pool in your Web application
Using the Redis database in the Go language
Date: 2016-09-13
Author: unknown
Original: Https://dinosaurscode.xyz/go/2016/09/13/using-go-with-redis/?utm_source=studygolang&utm_medium=email &nsukey=d7fohou2jwuvtnx567nmyebgiv3xa77y66gjwysuw6tbi9ltombwjlwazryvdyp1izh1mzzohcz%2bgh8xt%2fggttofelonx% 2fruumc%2b%2ft0eqnzrzljm7%2bkf8qnbq3zfhlnkq5zlfidb04jx4x98zpqshptxwx%2fouw8sfr18l2zkuq0szffhtafvwdtylcg1unfc
A Flower and a world
Date: 2016-10-23
Typography: The Mark Flying Elephant (Https://maxiang.io)
Body
In this example, you will see how to use Redis in go. First and foremost, the Redis service is connected with the following commands
$ go Get Github.com/garyburd/redigo
Next, make sure you've installed Redis and started the Redis server
$ redis-server
Connect to Redis
function Redis. Dial () returns a Redis. The type of conn that is used to send commands to the Redis server and return an answer.
package mainimport"fmt"import"github.com/garyburd/redigo/redis"func main() { // Connect to the default port conn, err := redis.Dial("tcp"":6379") ifnil { panic(err.Error()) } defer conn.Close() // Send Redis a ping command and wait for a pong pong, _ := conn.Do("PING") fmt.Println(pong) // Output: PONG}
Storing and retrieving data
Set a string
ok, _ := conn.Do("SET""name""john")fmt.Println(ok)// Output: OK
Take value
name, _ := conn.Do("GET""name")fmt.Println(name)// Output: [106 111 104 110]
Oh, no, that's not the result I want.
Sometimes, you want to explicitly turn the results into the appropriate type, which can be used with type assertions or Redigo helper functions.
// 注意用外层用redis.Stirng()封装name, _ := redis.String(conn.Do("GET""name"))fmt.Println(name)// Output: john
Decode into JSON
You can save a complex data type, such as a struct, in JSON format.
// 把结构体存在json结构中, 用列表的形式存取。type User struct { Name string Age int}user1User{"John"22}encoded, _ := json.Marshal(user1)conn.Do("LPUSH""users", encoded)
Now decode into a struct
//从redis中提取,并解码到一个结构中typestruct { string Age int}var// 把用户列表映射到一个名为users的字符串数组中users, _ := redis.Strings(conn.Do("LRANGE""users", 0, -1))// 抽取一个字符,然后把它转成字节类型,然后解码到unencodedjson.Unmarshal([]byte(users[0]), &unencoded)fmt.Println(unencoded.Name)// 输出: John
Finally, you should use a connection pool in your web App
The HTTP developer should get a connection from the connection pool and, when finished, close it.
PackageMainImport "Github.com/garyburd/redigo/redis"Import "Net/http"//Global pool that handlers can grab a connection fromvarPool = Newpool ()//Pool configurationfuncNewpool () *redis. Pool {return&redis. pool{Maxidle: the, Maxactive:12000, Dial:func() (Redis. Conn, error) {returnRedis. Dial ("TCP",": 6379") }, }}funcHome (res http. Responsewriter, req *http. Request) {//Grab a connection and make sure to close it with deferConn: = Pool. Get ()deferConn. Close () Pong, _: = Redis. Bytes (Conn. Do ("PING")) Res. Write (Pong)}funcMain () {http. Handlefunc ("/", home) http. Listenandserve (": 8080",Nil)}