-
Notifications
You must be signed in to change notification settings - Fork 0
/
redis.go
112 lines (99 loc) · 2.46 KB
/
redis.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
// Copyright 2015 realglobe, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package test
import (
"io/ioutil"
"os"
"os/exec"
"strconv"
"time"
"github.com/garyburd/redigo/redis"
"github.com/realglobe-Inc/go-lib/erro"
)
var (
// 実行可能な redis-server。
RedisPath = "redis-server"
)
type RedisServer struct {
pool *redis.Pool
conf string
addr string
}
func (this *RedisServer) Pool() *redis.Pool {
return this.pool
}
func (this *RedisServer) Address() string {
return this.addr
}
func (this *RedisServer) Close() {
conn := this.pool.Get()
conn.Do("SHUTDOWN")
conn.Close()
this.pool.Close()
os.Remove(this.conf)
}
func NewRedisServer() (*RedisServer, error) {
path, err := exec.LookPath(RedisPath)
if err != nil {
// 実行可能な redis-server が無い。
return nil, nil
}
port, err := FreePort()
if err != nil {
return nil, erro.Wrap(err)
}
file, err := ioutil.TempFile("", "edo-lib.test")
if err != nil {
return nil, erro.Wrap(err)
} else if _, err := file.Write([]byte("port " + strconv.Itoa(port))); err != nil {
return nil, erro.Wrap(err)
} else if err := file.Close(); err != nil {
return nil, erro.Wrap(err)
}
// 失敗したら設定ファイルは消す。
failed := true
defer func() {
if failed {
os.Remove(file.Name())
}
}()
cmd := exec.Command(path, file.Name())
errCh := make(chan error, 1)
go func() {
errCh <- cmd.Run()
}()
// 起動待ち。
for i := time.Nanosecond; ; i *= 2 {
if _, err := redis.Dial("tcp", ":"+strconv.Itoa(port)); err == nil {
break
}
select {
case err := <-errCh:
return nil, erro.Wrap(err)
case <-time.After(i):
}
}
failed = false
return &RedisServer{&redis.Pool{
MaxIdle: 5,
IdleTimeout: time.Minute,
Dial: func() (redis.Conn, error) {
return redis.Dial("tcp", ":"+strconv.Itoa(port))
},
TestOnBorrow: func(c redis.Conn, t time.Time) error {
_, err := c.Do("PING")
return err
},
}, file.Name(), ":" + strconv.Itoa(port)}, nil
}