-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrmqconn.go
101 lines (86 loc) · 2.23 KB
/
rmqconn.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
package rmqconn
import (
"fmt"
"os"
"github.com/sivaosorg/govm/dbx"
"github.com/sivaosorg/govm/logger"
"github.com/sivaosorg/govm/rabbitmqx"
"github.com/sivaosorg/govm/utils"
amqp "github.com/rabbitmq/amqp091-go"
)
var (
_logger = logger.NewLogger()
)
func NewRabbitMq() *RabbitMq {
r := &RabbitMq{}
return r
}
func (r *RabbitMq) SetConn(value *amqp.Connection) *RabbitMq {
r.conn = value
return r
}
func (r *RabbitMq) SetChannel(value *amqp.Channel) *RabbitMq {
r.channel = value
return r
}
func (r *RabbitMq) SetConfig(value rabbitmqx.RabbitMqConfig) *RabbitMq {
r.Config = value
return r
}
func (r *RabbitMq) SetClose(value bool) *RabbitMq {
r.close = value
return r
}
func (r *RabbitMq) SetState(value dbx.Dbx) *RabbitMq {
r.State = value
return r
}
func (r *RabbitMq) GetConn() *amqp.Connection {
return r.conn
}
func (r *RabbitMq) GetChannel() *amqp.Channel {
return r.channel
}
func (r *RabbitMq) Json() string {
return utils.ToJson(r)
}
func NewClient(config rabbitmqx.RabbitMqConfig) (*RabbitMq, dbx.Dbx) {
instance := NewRabbitMq()
s := dbx.NewDbx().SetDebugMode(config.DebugMode)
if !config.IsEnabled {
s.SetConnected(false).
SetMessage("RabbitMQ unavailable").
SetError(fmt.Errorf(s.Message))
instance.SetState(*s)
return instance, *s
}
if config.Timeout == 0 {
config.SetTimeout(10)
}
// conn, err := amqp.Dial(config.ToUrlConn())
conn, err := amqp.DialConfig(config.ToUrlConn(), amqp.Config{Dial: amqp.DefaultDial(config.Timeout)})
if err != nil {
s.SetConnected(false).SetError(err).SetMessage(err.Error())
instance.SetState(*s)
return instance, *s
}
channel, err := conn.Channel()
if err != nil {
s.SetConnected(false).SetError(err).SetMessage(err.Error())
instance.SetState(*s)
return instance, *s
}
if config.DebugMode {
_logger.Info(fmt.Sprintf("RabbitMQ client connection:: %s", config.Json()))
_logger.Info(fmt.Sprintf("Connected successfully to rabbitmq:: %s", config.ToUrlConn()))
}
pid := os.Getpid()
s.SetConnected(true).SetMessage("Connected successfully").SetPid(pid).SetNewInstance(true)
instance.SetConn(conn).SetChannel(channel).SetConfig(config).SetState(*s)
return instance, *s
}
func (c *RabbitMq) Close() {
c.SetClose(true)
c.conn.Close()
c.channel.Close()
}