This is a creation in Article, where the information may have evolved or changed.
Redis has a lot of clients, and the Go language client has two recommendations in the Redis official, Radix and Redigo. Which one is the best choice? Really tangled, and then toss the coin decided to choose Redigo.
Redis, go, Redigo installation does not need to mention, cannot forcibly increase the space.
Redigo is very user-friendly, API design in line with intuition, I know less about Redis, the use of the process of basic no obstacles.
Redigo can be used to check Godoc:http://godoc.org/github.com/garyburd/redigo/redis.
The next step is the no-tech sticker code:
Connect to Redis I usually write this way:
1 C, err: = Redis. Dial ("tcp""127.0.0.1:6379")2if Err! = Nil {3 FMT. PRINTLN (Err)4 return5}6 defer c.close ()
The Execute command uses the Do function, which is similar to the feeling of redis-cli knocking commands:
1V, err: = C.do ("SET","name","Red")2 ifErr! =Nil {3 FMT. PRINTLN (ERR)4 return5 }6 FMT. Println (v)7V, err = Redis. String (C.do ("GET","name"))8 ifErr! =Nil {9 FMT. PRINTLN (ERR)Ten return One } AFmt. Println (v)
The same is true for lists:
1C.do ("Lpush","Redlist","QQQ")2C.do ("Lpush","Redlist","www")3C.do ("Lpush","Redlist","Eee")
The Read list can be used for loop traversal or Redis. Scan function:
1Values, _: = Redis. Values (C.do ("Lrange","Redlist","0"," -"))2 3 for_, V: =Range Values {4Fmt. Println (string(v. ([]byte)))5 }6 7 //or8 varV1string9Redis. Scan (Values, &v1)TenFmt. Println (v1)
Pipeline:
1 c.send ( " set , " name , " Red ) c.send ( get ", " name " 3 4 c.receive () 5 c.receive ()
To publish a subscription:
1 Func Subscribe () {2C, err: = Redis. Dial ("TCP","127.0.0.1:6379")3 ifErr! =Nil {4 FMT. PRINTLN (ERR)5 return6 }7 defer c.close ()8 9PSC: =Redis. PUBSUBCONN{C}TenPsc. Subscribe ("Redchatroom") One for { A SwitchV: =PSC. Receive (). (type) { - CaseRedis. Message: -Fmt. Printf ("%s:message:%s\n", V.channel, V.data) the CaseRedis. Subscription: -Fmt. Printf ("%s:%s%d\n", V.channel, V.kind, V.count) - CaseError: - FMT. Println (v) + return - } + } A}
1 Go Subscribe ()2 Go Subscribe ()3 Go Subscribe ()4 Go Subscribe ()5 Go Subscribe ()6 7C, err: = Redis. Dial ("TCP","127.0.0.1:6379")8 ifErr! =Nil {9 FMT. PRINTLN (ERR)Ten return One } A defer c.close () - - for { the varSstring -Fmt. SCANLN (&s) -_, Err: = C.do ("PUBLISH","Redchatroom", s) - ifErr! =Nil { +Fmt. Println ("Pub ERR:", Err) - return + } A}
It's almost like that, and there's really nothing to explain ...