解决问题:当redis服务端断开的时候`进程会崩溃(转载6哥笔记)

 1 package main
 2 
 3 import (
 4     "fmt"
 5     "github.com/astaxie/beego/logs"
 6     "github.com/garyburd/redigo/redis"
 7     "ha666/initial"
 8     _ "ha666/initial"
 9     "strconv"
10     "time"
11 )
12 
13 func main() {
14     defer func() {
15         if err := recover(); err != nil {
16             logs.Error("【main】ex:%v", err)
17             time.Sleep(time.Second)
18         }
19     }()
20     logs.Info("开始")
21     rc := initial.RedisClient.Get()
22     defer rc.Close()
23     for {
24         bytesresult, err := redis.ByteSlices(rc.Do("TIME"))
25         if err != nil {
26             fmt.Println(err.Error())
27             return
28         }
29         for _, v := range bytesresult {
30             _, err = strconv.ParseInt(string(v), 10, 64)
31             if err != nil {
32                 fmt.Println(err.Error())
33                 return
34             }
35             //fmt.Println(il)
36         }
37         time.Sleep(10 * time.Millisecond)
38     }
39 }

上面犯了两个错误:

1、defer使用错误
2、redis客户端从pool取出来以后要判断错误
修正后的代码是这样的:
 1 package main
 2 
 3 import (
 4     "fmt"
 5     "github.com/astaxie/beego/logs"
 6     "github.com/garyburd/redigo/redis"
 7     "github.com/pkg/errors"
 8     "ha666/initial"
 9     _ "ha666/initial"
10     "strconv"
11     "time"
12 )
13 
14 func main() {
15     for {
16         bytesresult, err := get_redis()
17         if err != nil {
18             fmt.Println(err.Error())
19             continue
20         }
21         for _, v := range bytesresult {
22             il, err := strconv.ParseInt(string(v), 10, 64)
23             if err != nil {
24                 fmt.Println(err.Error())
25                 continue
26             }
27             fmt.Println(il)
28         }
29         time.Sleep(1000 * time.Millisecond)
30     }
31 }
32 
33 func get_redis() ([][]byte, error) {
34     rc := initial.RedisClient.Get()
35     if rc.Err() != nil {
36         return nil, rc.Err()
37     }
38     defer rc.Close()
39     bytesresult, err := redis.ByteSlices(rc.Do("TIME"))
40     return bytesresult, err
41 }

 

posted @ 2018-01-03 14:39  uint32  阅读(892)  评论(0编辑  收藏  举报