(转)go rabbitmq实践
转载自:http://www.cnblogs.com/shi-meng/p/4800080.html
1:驱动
本来打算自己写一个驱动的,后来发现github上面已经有了,那我就直接拿现成的了, 驱动采用 github.com/streadway/amqp ,直接import就可以啦!
2:exchange and queue
在上一篇文章中,我们已经创建好virtualhost 、exchange and queue,所以我们先定义这些常量

const (
queueName = "push.msg.q"
exchange = "t.msg.ex"
mqurl ="amqp://shi:123@192.168.232.130:5672/test"
)
var conn *amqp.Connection
var channel *amqp.Channel

3:错误处理
func failOnErr(err error, msg string ) { if err != nil { log.Fatalf( "%s:%s" , msg, err) panic(fmt.Sprintf( "%s:%s" , msg, err)) } } |
4:连接mq

func mqConnect() {
var err error
conn, err = amqp.Dial(mqurl)
failOnErr(err, "failed to connect tp rabbitmq") channel, err = conn.Channel()
failOnErr(err, "failed to open a channel")
}

5:push
先上代码:

func push() { if channel == nil {
mqConnect()
}
msgContent := "hello world!" channel.Publish(exchange, queueName, false, false, amqp.Publishing{
ContentType: "text/plain",
Body: []byte(msgContent),
})
}

其实是很简单的,调用 channel函数的Publish方法,传入exchange name 和 queue name,最后一个参数是消息内容,ContentType我们设置为text/plain, 为文本类型,body是消息内容,要传入字节数组,这样就完成了一条消息的push,接下来我们再看receive
6:receive
代码:

func receive() {
if channel == nil {
mqConnect()
} msgs, err := channel.Consume(queueName, "", true, false, false, false, nil)
failOnErr(err, "") forever := make(chan bool) go func() {
//fmt.Println(*msgs)
for d := range msgs {
s := BytesToString(&(d.Body))
count++
fmt.Printf("receve msg is :%s -- %d\n", *s, count)
}
}() fmt.Printf(" [*] Waiting for messages. To exit press CTRL+C\n")
<-forever
}

通过调用channel.Consume函数返回一个接受消息的chan类型管道,然后range 这个chan,接收到的数据是[]byte,转换为string后输出
<-forever 这个是为了控制当前线程不退出
7:入口main

func main() {
go func() {
for {
push()
time.Sleep(1 * time.Second)
}
}()
receive()
fmt.Println("end")
close()
}

for 循环保证每秒发送一条消息到mq,这个地方采用协程保证不阻塞主线程。receive函数不能采用协程,不然主线程就退出了。close函数是释放连接对象,但是在这个例子中是没有起效的,因为线程永远都不会自动退出,只能认为的CTRL+C 或者程序死掉,系统重启
8:执行:
切换到go文件目录执行

receve msg is :hello world! -- 1246
receve msg is :hello world! -- 1247
receve msg is :hello world! -- 1248
receve msg is :hello world! -- 1249
receve msg is :hello world! -- 1250
receve msg is :hello world! -- 1251
receve msg is :hello world! -- 1252
receve msg is :hello world! -- 1253
receve msg is :hello world! -- 1254
receve msg is :hello world! -- 1255
receve msg is :hello world! -- 1256
receve msg is :hello world! -- 1257
receve msg is :hello world! -- 1258
receve msg is :hello world! -- 1259
receve msg is :hello world! -- 1260
receve msg is :hello world! -- 1261
receve msg is :hello world! -- 1262
receve msg is :hello world! -- 1263
receve msg is :hello world! -- 1264
receve msg is :hello world! -- 1265
receve msg is :hello world! -- 1266

9:全部代码

package main import (
"fmt"
"log"
"bytes"
"time"
"github.com/streadway/amqp"
) var conn *amqp.Connection
var channel *amqp.Channel
var count = 0 const (
queueName = "push.msg.q"
exchange = "t.msg.ex"
mqurl ="amqp://shi:123@192.168.232.130:5672/test"
) func main() {
go func() {
for {
push()
time.Sleep(1 * time.Second)
}
}()
receive()
fmt.Println("end")
close()
} func failOnErr(err error, msg string) {
if err != nil {
log.Fatalf("%s:%s", msg, err)
panic(fmt.Sprintf("%s:%s", msg, err))
}
} func mqConnect() {
var err error
conn, err = amqp.Dial(mqurl)
failOnErr(err, "failed to connect tp rabbitmq") channel, err = conn.Channel()
failOnErr(err, "failed to open a channel")
} func close() {
channel.Close()
conn.Close()
} //连接rabbitmq server
func push() { if channel == nil {
mqConnect()
}
msgContent := "hello world!" channel.Publish(exchange, queueName, false, false, amqp.Publishing{
ContentType: "text/plain",
Body: []byte(msgContent),
})
} func receive() {
if channel == nil {
mqConnect()
} msgs, err := channel.Consume(queueName, "", true, false, false, false, nil)
failOnErr(err, "") forever := make(chan bool) go func() {
//fmt.Println(*msgs)
for d := range msgs {
s := BytesToString(&(d.Body))
count++
fmt.Printf("receve msg is :%s -- %d\n", *s, count)
}
}() fmt.Printf(" [*] Waiting for messages. To exit press CTRL+C\n")
<-forever
} func BytesToString(b *[]byte) *string {
s := bytes.NewBuffer(*b)
r := s.String()
return &r
}
(转)go rabbitmq实践的更多相关文章
- Docker 尝试安装rabbitmq实践笔记
docker pull rabbitmq 自定義的rabbitmq Dockerfile # base image FROM rabbitmq:3.7-management # running req ...
- Python操作rabbitmq 实践笔记
发布/订阅 系统 1.基本用法 生产者 import pika import sys username = 'wt' #指定远程rabbitmq的用户名密码 pwd = ' user_pwd = p ...
- NET下RabbitMQ实践[实战篇]
之前的文章中,介绍了如何将RabbitMQ以WCF方式进行发布.今天就介绍一下我们产品中如何使用RabbitMQ的! 在Discuz!NT企业版中,提供了对HTTP错误日志的记录功能 ...
- NET下RabbitMQ实践[配置篇]
这个系列目前计划写四篇,分别是配置,示例,WCF发布,实战.当然不排除加餐情况. 介绍: rabbitMQ是一个在AMQP协议标准基础上完整的,可服用的企业消息系统.他遵循Mozilla Publi ...
- NET下RabbitMQ实践[示例篇]
在上一篇文章中,介绍了在window环境下安装erlang,rabbitmq-server,以免配置用户,权限,虚拟机等内容. 今天将会介绍如果使用rabbitmq进行简单的消息入队, ...
- NET下RabbitMQ实践[WCF发布篇]
在之前的两篇文章中,主要介绍了RabbitMQ环境配置,简单示例的编写.今天将会介绍如何使用WCF将RabbitMQ列队以服务的方式进行发布. 注:因为RabbitMQ的官方.net ...
- RabbitMQ 实践及使用
目录 - 1. RabbitMQ的安装 - 1.1 配置好 epel - 1.2 安装 RPM包 - 1.3 创建用户设置权限- 2. RabbitMQ组件- 3. RabbitMQ ...
- rabbitmq实践笔记(一):安装、配置与使用初探
引言: 对于一个大型的软件系统来说,会有很多的组件.模块及不同的子系统一起协同工作,模块之间的通信需要一个可靠的通信管道来保证 ,通信管道需要解决解决很多问题,比如: 1)信息的发送者和接收者如何维持 ...
- RabbitMQ 实践之在处理异步任务中的流程
一.背景: 我司的系统,用户可以创建任务,启动任务,但任务的运行需要很长的时间,所以采用消息队列的方式,后台异步处理. 这里所用到的是 RabbitMQ . 二.MQ 处理任务的流程 ① ② ③ ④ ...
随机推荐
- 【一天一道LeetCode】#350. Intersection of Two Arrays II
一天一道LeetCode 本系列文章已全部上传至我的github,地址:ZeeCoder's Github 欢迎大家关注我的新浪微博,我的新浪微博 欢迎转载,转载请注明出处 (一)题目 Given t ...
- [GitHub]第八讲:GitHub Pages
Github Pages 是 github 公司提供的免费的静态网站托管服务,用起来方便而且功能强大,不仅没有空间限制,还可以绑定自己的域名.在 https://pages.github.com/ 首 ...
- 未完成的IT路停在回车键---2014年末总结篇
时间都去哪儿了? 一晃而过,越来越能体会到这个词的真实感.特别是过了二十岁,这种感觉越来越深刻,越来越强烈,犹如小编做公交车的时候一直向后排排倒的香樟树,还记得有首歌叫时间都哪儿了,而 ...
- springMVC对异常处理的支持
无论做什么项目,进行异常处理都是非常有必要的,而且你不能把一些只有程序员才能看懂的错误代码抛给用户去看,所以这时候进行统一的异常处理,展现一个比较友好的错误页面就显得很有必要了.跟其他MVC框架一样, ...
- ROS_Kinetic_19 群机器人框架示例(micros swarm framework)
ROS_Kinetic_19 群机器人框架示例(micros swarm framework) 官方网址:http://wiki.ros.org/micros_swarm_framework 这个包是 ...
- 【一天一道LeetCode】#64. Minimum Path Sum.md
一天一道LeetCode 本系列文章已全部上传至我的github,地址:ZeeCoder's Github 欢迎大家关注我的新浪微博,我的新浪微博 欢迎转载,转载请注明出处 (一)题目 Given a ...
- Oracle Forms Services Architecture
Oracle Forms Services Architecture Author: PTIAN(tianpan@gmail.com) Creation ...
- 匿名函数,结合闭包的写法,js对象的案例
/* * name :Zuoquan Tu * mail :tuzq@XXX.com.cn * date :2015/04/1 * version :1.1 * description:modifie ...
- Android群英传帝落篇——程序人生,路漫漫其修远兮,吾将上下而求索!
Android群英传帝落篇--程序人生,路漫漫其修远兮,吾将上下而求索! 当写这篇博客的时候,自2016-02-22到现在5.2号,一晃眼,也㓟两个多月就过去了,我才将这本书看完,虽然写笔记花了很大的 ...
- ffdshow 源代码分析 6: 对解码器的dll的封装(libavcodec)
===================================================== ffdshow源代码分析系列文章列表: ffdshow 源代码分析 1: 整体结构 ffds ...