Add en/redigo demo

This commit is contained in:
vCaesar
2017-01-07 19:04:20 +08:00
parent 1c386c6a54
commit 2f732d86bd
2 changed files with 79 additions and 1 deletions

View File

@@ -15,6 +15,84 @@ There are some Go database drivers for redis:
- [https://github.com/simonz05/godis](https://github.com/simonz05/godis)
- [https://github.com/hoisie/redis.go](https://github.com/hoisie/redis.go)
Let's see how to use the driver that redigo to operate on a database:
```Go
package main
import (
"fmt"
"github.com/garyburd/redigo/redis"
"os"
"os/signal"
"syscall"
"time"
)
var (
Pool *redis.Pool
)
func init() {
redisHost := ":6379"
Pool = newPool(redisHost)
close()
}
func newPool(server string) *redis.Pool {
return &redis.Pool{
MaxIdle: 3,
IdleTimeout: 240 * time.Second,
Dial: func() (redis.Conn, error) {
c, err := redis.Dial("tcp", server)
if err != nil {
return nil, err
}
return c, err
},
TestOnBorrow: func(c redis.Conn, t time.Time) error {
_, err := c.Do("PING")
return err
},
}
}
func close() {
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
signal.Notify(c, syscall.SIGTERM)
signal.Notify(c, syscall.SIGKILL)
go func() {
<-c
Pool.Close()
os.Exit(0)
}()
}
func Get(key string) ([]byte, error) {
conn := Pool.Get()
defer conn.Close()
var data []byte
data, err := redis.Bytes(conn.Do("GET", key))
if err != nil {
return data, fmt.Errorf("error get key %s: %v", key, err)
}
return data, err
}
func main() {
test, err := Get("test")
fmt.Println(test, err)
}
```
I forked the last of these packages, fixed some bugs, and used it in my short URL service (2 million PV every day).
- [https://github.com/astaxie/goredis](https://github.com/astaxie/goredis)

View File

@@ -18,7 +18,7 @@ Go目前支持redis的驱动有如下
我以redigo驱动为例来演示如何进行数据的操作:
```Go
package redis
package main
import (
"fmt"