连接redis
package main
import (
"fmt"
"github.com/garyburd/redigo/redis"
)
func main() {
c, err := redis.Dial("tcp", "localhost:6379")
if err != nil {
fmt.Println("conn redis failed,", err)
return
}
fmt.Println("redis conn success")
defer c.Close()
}
执行redis语句
package main
import (
"fmt"
"github.com/garyburd/redigo/redis"
)
func main() {
c, err := redis.Dial("tcp", "localhost:6379")
defer c.Close()
if err != nil {
fmt.Println("conn redis failed,", err)
return
}
r, _ := c.Do("set", "name", "mac") //这里写redis语句
fmt.Println(r)
res, _ := redis.String(c.Do("get", "name"))
fmt.Println(res)
}
package main
import (
"fmt"
"github.com/garyburd/redigo/redis"
)
func main() {
c, err := redis.Dial("tcp", "localhost:6379")
defer c.Close()
if err != nil {
fmt.Println("conn redis failed,", err)
return
}
c.Send("set", "name", "mac")
c.Send("set", "age", 18)
c.Send("get", "name")
c.Send("get", "age")
c.Flush()
res, _ := redis.String(c.Receive())
fmt.Println(res)
res, _ = redis.String(c.Receive())
fmt.Println(res)
res, _ = redis.String(c.Receive())
fmt.Println(res)
res, _ = redis.String(c.Receive())
fmt.Println(res)
}
publish&subscribe
package main
import (
"fmt"
"github.com/garyburd/redigo/redis"
"time"
)
func publish() {
c2, err := redis.Dial("tcp", "localhost:6379")
if err != nil {
}
for {
var t string = "现在时间为: "
t += time.Now().String()
c2.Do("publish", "bbc", t)
time.Sleep(time.Second)
}
}
func main() {
c, err := redis.Dial("tcp", "localhost:6379")
defer c.Close()
if err != nil {
fmt.Println("conn redis failed,", err)
return
}
psc := redis.PubSubConn{
Conn: c,
}
psc.Subscribe("bbc")
go publish()
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:
return
}
}
}
scan用法
func main() {
c, err := redis.Dial("tcp", "localhost:6379")
defer c.Close()
if err != nil {
fmt.Println("conn redis failed,", err)
return
}
c.Do("mset", "name", "mac", "age", 18)
reply, _ := redis.Values(c.Do("mget", "name", "age"))
var age int
var name string
redis.Scan(reply, &name, &age)
fmt.Println(name, age)
}
连接池
package main
import(
"fmt"
"github.com/garyburd/redigo/redis"
)
var pool *redis.Pool //创建redis连接池
func init(){
pool = &redis.Pool{ //实例化一个连接池
MaxIdle:16, //最初的连接数量
// MaxActive:1000000, //最大连接数量
MaxActive:0, //连接池最大连接数量,不确定可以用0(0表示自动定义),按需分配
IdleTimeout:300, //连接关闭时间 300秒 (300秒不使用自动关闭)
Dial: func() (redis.Conn ,error){ //要连接的redis数据库
return redis.Dial("tcp","localhost:6379")
},
}
}
func main(){
c := pool.Get() //从连接池,取一个链接
defer c.Close() //函数运行结束 ,把连接放回连接池
_,err := c.Do("Set","abc",200)
if err != nil {
fmt.Println(err)
return
}
r,err := redis.Int(c.Do("Get","abc"))
if err != nil {
fmt.Println("get abc faild :",err)
return
}
fmt.Println(r)
pool.Close() //关闭连接池
}