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
| package rabbitmq
import ( "encoding/json" "github.com/rabbitmq/amqp091-go" )
type RabbitMQ struct { channel *amqp091.Channel Name string exchange string }
func New(s string) *RabbitMQ { conn, err := amqp091.Dial(s) if err != nil { panic(err) }
channel, e := conn.Channel() if e != nil { panic(e) }
q, e := channel.QueueDeclare( "", false, true, false, false, nil, )
if e != nil { panic(e) }
mq := new(RabbitMQ) mq.channel = channel mq.Name = q.Name return mq }
func (q *RabbitMQ) Bind(exchange string) { e := q.channel.QueueBind( q.Name, "", exchange, false, nil, ) if e != nil { panic(e) } q.exchange = exchange }
func (q *RabbitMQ) Send(queue string, body interface{}) { str, e := json.Marshal(body) if e != nil { panic(e) } e = q.channel.Publish( "", queue, false, false, amqp091.Publishing{ ReplyTo: q.Name, Body: []byte(str), }) if e != nil { panic(e) } }
func (q *RabbitMQ) Publish(exchange string, body interface{}) { str, e := json.Marshal(body) if e != nil { panic(e) }
e = q.channel.Publish( exchange, "", false, false, amqp091.Publishing{ ReplyTo: q.Name, Body: []byte(str), }) if e != nil { panic(e) }
}
func (q *RabbitMQ) Consume() <-chan amqp091.Delivery { c, e := q.channel.Consume( q.Name, "", true, false, false, false, nil, ) if e != nil { panic(e) } return c }
func (q *RabbitMQ) Close() { q.channel.Close() }
|