我的代码感觉和你的一样,但是消费者无法接收消息呢?
来源:3-6 RabbitMQ工作模式---Simple模式(下)
慕勒5271768
2019-07-14
rabbitmq.go
package rabbitmq
import (
"fmt"
"github.com/streadway/amqp"
"log"
)
const MQURL = "amqp://imoocuser:imoocuser@127.0.0.1:5672/imooc"
type RabbitMQ struct {
conn *amqp.Connection
channel *amqp.Channel
QueueName string
Exchange string
Key string
Mqurl string
}
func NewRabbitMq(queuenName string, exchange string, key string) *RabbitMQ {
rabbitmq := &RabbitMQ{QueueName: queuenName, Exchange: exchange, Key: key, Mqurl: MQURL}
var err error
rabbitmq.conn, err = amqp.Dial(rabbitmq.Mqurl)
rabbitmq.failOnErr(err, "conn error")
rabbitmq.channel, err = rabbitmq.conn.Channel()
rabbitmq.failOnErr(err, "channle error")
return rabbitmq
}
func (r *RabbitMQ) Destroy() {
r.channel.Close()
r.conn.Close()
}
//错误处理
func (r *RabbitMQ) failOnErr(err error, message string) {
if err != nil {
log.Fatalf("%s:%s", message, err)
}
}
//简单模式
func NewSimpleRabbitMq(queneName string) *RabbitMQ {
return NewRabbitMq(queneName, "", "")
}
//简单模式下生产者
func (r *RabbitMQ) PublishSimple(message string) {
//申请队列
_, err := r.channel.QueueDeclare(
r.QueueName,
false,
false,
false,
false,
nil)
if err != nil {
fmt.Println(err)
}
//发送消息到队列
err=r.channel.Publish(
r.Exchange,
r.Key,
false,
false,
amqp.Publishing{
ContentType: "text/plain",
Body: []byte(message),
},
)
if err!=nil{
fmt.Println(err)
return
}
}
//简单模式下消费者
func (r *RabbitMQ) ConsumerSimple() {
//申请队列
_, err := r.channel.QueueDeclare(
r.QueueName,
false,
false,
false,
false,
nil)
if err != nil {
fmt.Println(err)
}
//接收消息
msgs, err := r.channel.Consume(r.QueueName, "", true, false, false, false, nil)
if err != nil {
fmt.Println(err)
}
forever := make(chan bool)
go func() {
for d := range msgs {
log.Printf("receive a message:%s\n",d.Body)
fmt.Println(d.Body)
}
}()
log.Printf("[*]Waiting for messages,To exit press CTRL+C\n")
<-forever
}
consumer.go
package main
import rabbitmq2 "rabbitmq/rabbitmq"
func main() {
rabbitmq:=rabbitmq2.NewSimpleRabbitMq(""+"imoocSimple")
rabbitmq.ConsumerSimple()
}
publish.go
package main
import (
"fmt"
"rabbitmq/rabbitmq"
)
func main() {
rabbitmq:=rabbitmq.NewSimpleRabbitMq(""+"imoocSimple")
rabbitmq.PublishSimple("hello saxoned!")
fmt.Println("发送成功!")
}
写回答
3回答
-
qq_ForgottenArm_0
2019-09-07
我也遇到了这个问题,可以将r.channel.Publish中的第二个参数改为r.QueueName就好了。奇怪的是,Publish函数签名提示是key,为什么需要改成r.QueueName?
022019-11-10 -
白小九jiu
2019-07-16
我也遇到这个问题诶,在Windows环境下运行,报错提示:创建连接错误!:Exception (403)Reason:“username or password not allowed”
题主的解决了吗???
012019-07-16 -
Cap
2019-07-15
具体信息是否可以通过QQ发我下?
00
相似问题