### golang 使用 redigo 库链接Redis
### 订阅:
```go
func subs() {
//订阅
conn := pool.Get()
defer conn.Close()
fmt.Println("接收消息....")
psc := redis.PubSubConn{conn}
_ = psc.Subscribe("chan_go")
for{
switch v := psc.Receive().(type) {
case redis.Message:
fmt.Printf("%s: message: %s\n", v.Channel, v.Data)
case redis.Subscription:
fmt.Printf("%s: %s %d\n", v.Channel, v.Kind, v.Count)
case error:
fmt.Println(v)
return
}
}
}
```
### 发布:
```go
func push(message string) {
//发布消息
conn := pool.Get()
defer conn.Close()
fmt.Println("发布消息....")
_,err := conn.Do("Publish","chan_go",message)
if err != nil{
fmt.Println(err)
return
}
}
```
### 连接池:
```go
func inits() {
pool = &redis.Pool{
MaxIdle: 8,
IdleTimeout: 100,
Dial: func() (redis.Conn, error) {
c, err := redis.Dial("tcp", "127.0.0.1:6379")
if err != nil {
return nil, err
}
return c, err
},
}
}
```
### 所有代码
```go
package main
import (
"fmt"
"github.com/garyburd/redigo/redis"
"time"
)
var pool *redis.Pool
func main() {
inits()
go subs()
go push("this is wd")
time.Sleep(3 * time.Second)
fmt.Println("Redis----")
}
//建立连接池
func inits() {
pool = &redis.Pool{
MaxIdle: 8,
IdleTimeout: 100,
Dial: func() (redis.Conn, error) {
c, err := redis.Dial("tcp", "127.0.0.1:6379")
if err != nil {
return nil, err
}
return c, err
},
}
}
//订阅
func subs() {
//订阅
conn := pool.Get()
defer conn.Close()
fmt.Println("接收消息....")
psc := redis.PubSubConn{conn}
_ = psc.Subscribe("chan_go")
for{
switch v := psc.Receive().(type) {
case redis.Message:
fmt.Printf("%s: message: %s\n", v.Channel, v.Data)
case redis.Subscription:
fmt.Printf("%s: %s %d\n", v.Channel, v.Kind, v.Count)
case error:
fmt.Println(v)
return
}
}
}
//发布消息
func push(message string) {
//发布消息
conn := pool.Get()
defer conn.Close()
fmt.Println("发布消息....")
_,err := conn.Do("Publish","chan_go",message)
if err != nil{
fmt.Println(err)
return
}
}
```
有疑问加站长微信联系(非本文作者))