-
Notifications
You must be signed in to change notification settings - Fork 11
/
redisstorage.go
151 lines (132 loc) · 3.79 KB
/
redisstorage.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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
package redisstorage
import (
"fmt"
"log"
"net/url"
"sync"
"time"
"github.com/go-redis/redis"
)
// Storage implements the redis storage backend for Colly
type Storage struct {
// Address is the redis server address
Address string
// Password is the password for the redis server
Password string
// DB is the redis database. Default is 0
DB int
// Prefix is an optional string in the keys. It can be used
// to use one redis database for independent scraping tasks.
Prefix string
// Client is the redis connection
Client *redis.Client
// Expiration time for Visited keys. After expiration pages
// are to be visited again.
Expires time.Duration
mu sync.RWMutex // Only used for cookie methods.
}
// Init initializes the redis storage
func (s *Storage) Init() error {
if s.Client == nil {
s.Client = redis.NewClient(&redis.Options{
Addr: s.Address,
Password: s.Password,
DB: s.DB,
})
}
_, err := s.Client.Ping().Result()
if err != nil {
return fmt.Errorf("Redis connection error: %s", err.Error())
}
return err
}
// Clear removes all entries from the storage
func (s *Storage) Clear() error {
s.mu.Lock()
defer s.mu.Unlock()
r := s.Client.Keys(s.getCookieID("*"))
keys, err := r.Result()
if err != nil {
return err
}
r2 := s.Client.Keys(s.Prefix + ":request:*")
keys2, err := r2.Result()
if err != nil {
return err
}
keys = append(keys, keys2...)
keys = append(keys, s.getQueueID())
return s.Client.Del(keys...).Err()
}
// Visited implements colly/storage.Visited()
func (s *Storage) Visited(requestID uint64) error {
return s.Client.Set(s.getIDStr(requestID), "1", s.Expires).Err()
}
// IsVisited implements colly/storage.IsVisited()
func (s *Storage) IsVisited(requestID uint64) (bool, error) {
_, err := s.Client.Get(s.getIDStr(requestID)).Result()
if err == redis.Nil {
return false, nil
} else if err != nil {
return false, err
}
return true, nil
}
// SetCookies implements colly/storage..SetCookies()
func (s *Storage) SetCookies(u *url.URL, cookies string) {
// TODO(js) Cookie methods currently have no way to return an error.
// We need to use a write lock to prevent a race in the db:
// if two callers set cookies in a very small window of time,
// it is possible to drop the new cookies from one caller
// ('last update wins' == best avoided).
s.mu.Lock()
defer s.mu.Unlock()
// return s.Client.Set(s.getCookieID(u.Host), stringify(cnew), 0).Err()
err := s.Client.Set(s.getCookieID(u.Host), cookies, 0).Err()
if err != nil {
// return nil
log.Printf("SetCookies() .Set error %s", err)
return
}
}
// Cookies implements colly/storage.Cookies()
func (s *Storage) Cookies(u *url.URL) string {
// TODO(js) Cookie methods currently have no way to return an error.
s.mu.RLock()
cookiesStr, err := s.Client.Get(s.getCookieID(u.Host)).Result()
s.mu.RUnlock()
if err == redis.Nil {
cookiesStr = ""
} else if err != nil {
// return nil, err
log.Printf("Cookies() .Get error %s", err)
return ""
}
return cookiesStr
}
// AddRequest implements queue.Storage.AddRequest() function
func (s *Storage) AddRequest(r []byte) error {
return s.Client.RPush(s.getQueueID(), r).Err()
}
// GetRequest implements queue.Storage.GetRequest() function
func (s *Storage) GetRequest() ([]byte, error) {
r, err := s.Client.LPop(s.getQueueID()).Bytes()
if err != nil {
return nil, err
}
return r, err
}
// QueueSize implements queue.Storage.QueueSize() function
func (s *Storage) QueueSize() (int, error) {
i, err := s.Client.LLen(s.getQueueID()).Result()
return int(i), err
}
func (s *Storage) getIDStr(ID uint64) string {
return fmt.Sprintf("%s:request:%d", s.Prefix, ID)
}
func (s *Storage) getCookieID(c string) string {
return fmt.Sprintf("%s:cookie:%s", s.Prefix, c)
}
func (s *Storage) getQueueID() string {
return fmt.Sprintf("%s:queue", s.Prefix)
}