-
Notifications
You must be signed in to change notification settings - Fork 3
/
pool.go
121 lines (104 loc) · 2.52 KB
/
pool.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
package main
import (
"log"
"math/rand"
"strings"
"sync"
"time"
"github.com/go-resty/resty/v2"
)
var proxies sync.Map
// 加载代理工厂
func LoadProxyFactory() {
// 加载代理的Ticker
loadTicker := time.NewTicker(time.Duration(config.IntervalTime) * time.Second)
//defer loadTicker.Stop()
// 删除过期代理的Ticker
removeTicker := time.NewTicker(time.Duration(config.IntervalTime) * time.Second)
//defer removeTicker.Stop()
// 启动一个 goroutine 来处理定时器事件
go func() {
for {
select {
case <-loadTicker.C:
PullProxy()
case <-removeTicker.C:
RemoveExpProxy()
}
}
}()
}
// 获取随机代理
//
// @return string
func GetRandomPorxy() string {
// 设置随机数种子
rand.NewSource(time.Now().UnixNano())
// 随机获取一个键
var randomKey string
proxies.Range(func(key, value interface{}) bool {
if rand.Intn(2) == 0 {
randomKey = key.(string)
return false // 停止遍历
}
return true
})
//proxies.Delete(randomKey)
return randomKey
}
// 拉取代理
func PullProxy() {
client := resty.New()
resp, err := client.R().
Get(config.ProxyUrl)
if err != nil {
log.Print("Pull Proxy Error:", err)
}
var storeCout int
currentTime := time.Now()
newTime := currentTime.Add(time.Duration(config.ExpTime) * time.Second)
proxyArray := strings.Split(string(resp.Body()), "\n")
for _, proxy := range proxyArray {
_, found := proxies.Load(strings.Replace(proxy, "\r", "", -1))
if !found {
if !IsInternalIP(strings.Split(proxy, ":")[0]) {
proxies.Store(strings.Replace(proxy, "\r", "", -1), newTime)
storeCout++
}
}
}
if storeCout != 0 {
log.Printf("Loaded %v new proxies. Total: %v.", storeCout, GetProxiesCount())
}
}
// GetProxiesCount
// 获取代理池数量
//
// @return int 数量
func GetProxiesCount() int {
count := 0
proxies.Range(func(key, value interface{}) bool {
count++
return true
})
return count
}
// 删除过期代理
func RemoveExpProxy() {
now := time.Now()
var expiredProxies []string
proxies.Range(func(key, value interface{}) bool {
v, _ := value.(time.Time)
k, _ := key.(string)
if v.Before(now) {
expiredProxies = append(expiredProxies, k)
}
return true
})
for _, proxy := range expiredProxies {
proxies.Delete(proxy)
}
if len(expiredProxies) != 0 && config.DetailLog {
log.Printf("Remove %v expired proxies. Total: %v.", len(expiredProxies), GetProxiesCount())
}
}