-
Notifications
You must be signed in to change notification settings - Fork 3
/
client.go
153 lines (123 loc) · 2.31 KB
/
client.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
152
153
package rabbitmq
import (
"fmt"
"sync"
"github.com/streadway/amqp"
)
type RabbitMQClient struct {
Ch *amqp.Channel
ExName string
QueueName string
}
type Config struct {
User string
Password string
Host string
Port int
VHost string
}
type SendConfig struct {
Config
ExName string
}
type RecvConfig struct {
Config
ExName string
QueueName string
RouteKey string
}
var clientMap map[string]*RabbitMQClient = make(map[string]*RabbitMQClient)
var mu sync.Mutex
func NewSendClient(c SendConfig) (*RabbitMQClient, error) {
key := fmt.Sprintf("Send_%s_%s_%s_%d_%s", c.User, c.Password, c.Host, c.Port, c.ExName)
if client, ok := clientMap[key]; ok {
return client, nil
}
mu.Lock()
if client, ok := clientMap[key]; ok {
return client, nil
}
client, err := newClient(Config{c.User, c.Password, c.Host, c.Port, c.VHost})
if err != nil {
return nil, err
}
client.ExName = c.ExName
err = client.Ch.ExchangeDeclare(
c.ExName,
"topic",
true,
false,
false,
false,
nil,
)
if err != nil {
return nil, err
}
clientMap[key] = client
mu.Unlock()
return client, nil
}
func NewRecvClient(c RecvConfig) (*RabbitMQClient, error) {
key := fmt.Sprintf("Recv_%s_%s_%s_%d_%s_%s", c.User, c.Password, c.Host, c.Port, c.ExName, c.VHost)
if client, ok := clientMap[key]; ok {
return client, nil
}
mu.Lock()
if client, ok := clientMap[key]; ok {
return client, nil
}
client, err := newClient(Config{c.User, c.Password, c.Host, c.Port, c.VHost})
if err != nil {
return nil, err
}
client.QueueName = c.QueueName
err = client.Ch.ExchangeDeclare(
c.ExName,
"topic",
true,
false,
false,
false,
nil,
)
if err != nil {
return nil, err
}
_, err = client.Ch.QueueDeclare(
"",
false,
false,
true,
false,
nil,
)
if err != nil {
return nil, err
}
err = client.Ch.QueueBind(
c.QueueName,
c.RouteKey,
c.ExName,
false,
nil,
)
clientMap[key] = client
mu.Unlock()
return client, nil
}
func newClient(c Config) (*RabbitMQClient, error) {
connStr := fmt.Sprintf("amqp://%s:%s@%s:%d/%s", c.User, c.Password, c.Host, c.Port, c.VHost)
conn, err := amqp.Dial(connStr)
if err != nil {
return nil, err
}
ch, err := conn.Channel()
if err != nil {
return nil, err
}
client := &RabbitMQClient{
Ch: ch,
}
return client, nil
}