rabbitmq简单收发服务搭建
消息发送、接收简单代码示例
mq.xml
//rabbitmq config
spring.rabbitmq.host=ip:port
spring.rabbitmq.username=
spring.rabbitmq.password=
spring.rabbitmq.virtual-host=
//发送队列
send.exchange.name=
send.queue.name=
//接收
listen.queue.name.system=
@Configuration
public class AmqpConfig {
@Value("${spring.rabbitmq.host}")
private String address;
@Value("${spring.rabbitmq.username}")
private String username;
@Value("${spring.rabbitmq.password}")
private String password;
@Value("${spring.rabbitmq.virtual-host}")
private String virtualHost;
@Bean
public ConnectionFactory connectionFactory() {
CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
connectionFactory.setAddresses(address);
connectionFactory.setUsername(username);
connectionFactory.setPassword(password);
connectionFactory.setVirtualHost(virtualHost);
connectionFactory.setPublisherConfirms(true); //必须要设置、消息发送确认
return connectionFactory;
}
/**
* 常用spring为singleton单例模式,此处mq消息需将其改为非单例模式
*/
@Bean
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)//必须是prototype类型
public RabbitTemplate rabbitTemplate() {
return new RabbitTemplate(connectionFactory());
}
@Bean
public RabbitAdmin rabbitAdmin(ConnectionFactory connectionFactory) {
return new RabbitAdmin(connectionFactory);
}
}
//消息发送
@Component
public class SystemMqMessageSender {
private static final Logger logger = LoggerFactory.getLogger(SystemMqMessageSender.class);
@Autowired
private AmqpTemplate rabbitTemplate;
@Value("${send.exchange.name}")
private String exchangeSystem;
@Value("${send.queue.name}")
private String queueSystem;
@Resource
private RabbitAdmin rabbitAdmin;
public void sendMessage(EventModel eventModel) {
String message = JsonUtils.json(eventModel);
logger.info("发送消息:{}", message);
rabbitTemplate.convertAndSend(exchangeSystem, queueSystem, message);
}
//声明持久化队列,并绑定到exchange上
@Bean
public Binding bindingExchangeSystem() {
Queue queue = QueueBuilder.durable(queueSystem).build();//队列持久化
rabbitAdmin.declareQueue(queue);//声明队列
DirectExchange exchange = (DirectExchange) ExchangeBuilder.directExchange(exchangeSystem).build();
rabbitAdmin.declareExchange(exchange);//创建路由
Binding binding = BindingBuilder.bind(queue).to(exchange).withQueueName();//绑定路由
rabbitAdmin.declareBinding(binding);
return binding;
}
}
//消息接收
@Component
@RabbitListener(queues = "${listen.queue.name.system}")
public class SystemMessageListener extends BaseListener implements EventModelConsumer,InitializingBean {
private static final Logger logger = LoggerFactory.getLogger(SystemMessageListener.class);
@Value("${listen.queue.name.system}")
private String queueName;
@RabbitHandler
public void process(String message) {//监听消息
logger.info("接收到消息:{}", message);
processMessage(message, queueName);
}
public void processMessage(String content, String queueName) {
//业务处理
}
}
rabbitmq如何保证高可用呢
答案是消息应答机制,一下是rabbitmq消息应答机制的原文:
Doing a task can take a few seconds. You may wonder what happens if one of the consumers starts a long task and dies with it only partly done. With our current code, once RabbitMQ delivers a message to the customer it immediately marks it for deletion. In this case, if you kill a worker we will lose the message it was just processing. We'll also lose all the messages that were dispatched to this particular worker but were not yet handled.
But we don't want to lose any tasks. If a worker dies, we'd like the task to be delivered to another worker.
In order to make sure a message is never lost, RabbitMQ supports message acknowledgments. An ack(nowledgement) is sent back by the consumer to tell RabbitMQ that a particular message has been received, processed and that RabbitMQ is free to delete it.
If a consumer dies (its channel is closed, connection is closed, or TCP connection is lost) without sending an ack, RabbitMQ will understand that a message wasn't processed fully and will re-queue it. If there are other consumers online at the same time, it will then quickly redeliver it to another consumer. That way you can be sure that no message is lost, even if the workers occasionally die.
There aren't any message timeouts; RabbitMQ will redeliver the message when the consumer dies. It's fine even if processing a message takes a very, very long time.
Manual message acknowledgments are turned on by default. In previous examples we explicitly turned them off via the autoAck=true flag. It's time to set this flag to false and send a proper acknowledgment from the worker, once we're done with a task.
执行一个任务可能需要花费几秒钟,你可能会担心如果一个消费者在执行任务过程中挂掉了。一旦RabbitMQ将消息分发给了消费者,就会从内存中删除。在这种情况下,如果正在执行任务的消费者宕机,会丢失正在处理的消息和分发给这个消费者但尚未处理的消息。
但是,我们不想丢失任何任务,如果有一个消费者挂掉了,那么我们应该将分发给它的任务交付给另一个消费者去处理。
为了确保消息不会丢失,RabbitMQ支持消息应答。消费者发送一个消息应答,告诉RabbitMQ这个消息已经接收并且处理完毕了。RabbitMQ就可以删除它了。
如果一个消费者挂掉却没有发送应答,RabbitMQ会理解为这个消息没有处理完全,然后交给另一个消费者去重新处理。这样,你就可以确认即使消费者偶尔挂掉也不会丢失任何消息了。
没有任何消息超时限制;只有当消费者挂掉时,RabbitMQ才会重新投递。即使处理一条消息会花费很长的时间。
消息应答是默认打开的。我们通过显示的设置autoAsk=true关闭这种机制。现即自动应答开,一旦我们完成任务,消费者会自动发送应答。通知RabbitMQ消息已被处理,可以从内存删除。如果消费者因宕机或链接失败等原因没有发送ACK(不同于ActiveMQ,在RabbitMQ里,消息没有过期的概念),则RabbitMQ会将消息重新发送给其他监听在队列的下一个消费者。
rabbitmq简单收发服务搭建的更多相关文章
- mysql简单复制服务搭建
.安装mysql源(centos7中默认是不包含mysql源) wget http://repo.mysql.com/mysql-community-release-el7-5.noarch.rpm ...
- 用nodejs搭建一个简单的服务监听程序
作为一个从业三年左右的,并且从事过半年左右PHP开发工作的前端,对于后台,尤其是对以js语言进行开发的nodejs,那是比较有兴趣的,虽然本身并没有接触过相关的工作,只是自己私下做的一下小实验,但是还 ...
- 搭建简单Django服务并通过HttpRequester实现GET/POST http请求提交表单
调试Django框架写的服务时,需要模拟客户端发送POST请求,然而浏览器只能模拟简单的GET请求(将参数写在url内),网上搜索得到了HttpRequester这一firefox插件,完美的实现了模 ...
- SpringBoot + Dubbo + zookeeper 搭建简单分布式服务
SpringBoot + Dubbo + zookeeper 搭建简单分布式服务 详细操作及源码见: https://github.com/BillyYangOne/dubbo-springboot
- 高可用rabbitmq集群服务部署步骤
消息队列是非常基础的关键服务,为保证公司队列服务的高可用及负载均衡,现通过如下方式实现: RabbitMQ Cluster + Queue HA + Haproxy + Keepalived 3台ra ...
- Linux 邮件服务搭建
Linux 邮件服务搭建 邮件服务针对,在大型企业使用的比较多,一般小型企业都会买一些邮件服务,或者使用一些免费的邮件服务,达到我们使用的需求,并且不需要自己维护,下面我就来简单安装一下两个邮箱的案例 ...
- 通过集群的方式解决基于MQTT协议的RabbitMQ消息收发
在完成了基于AMQP协议的RabbitMQ消息收发后,我们要继续实现基于MQTT协议的RabbitMQ消息收发. 由于C#的RabbitMQ.Client包中只实现了基于AMQP协议的消息收发功能的封 ...
- 基于Netty与RabbitMQ的消息服务
Netty作为一个高性能的异步网络开发框架,可以作为各种服务的开发框架. 前段时间的一个项目涉及到硬件设备实时数据的采集,采用Netty作为采集服务的实现框架,同时使用RabbitMQ作为采集服务和各 ...
- WCFRESTFul服务搭建及实现增删改查
WCFRESTFul服务搭建及实现增删改查 RESTful Wcf是一种基于Http协议的服务架构风格, RESTful 的服务通常是架构层面上的考虑. 因为它天生就具有很好的跨平台跨语言的集成能力 ...
随机推荐
- JDK8的新特性——Lambda表达式
JDK8已经发布快4年的时间了,现在来谈它的新特性显得略微的有点“不合时宜”.尽管JDK8已不再“新”,但它的重要特性之一——Lambda表达式依然是不被大部分开发者所熟练运用,甚至不被开发者所熟知. ...
- SeleniumIDE_初识
版权声明:本文为博主原创文章,转载请注明出处. 学习Selenium,除了自己手动编写脚本,还可以使用Selenium IDE进行脚本录制. 安装Selenium IDE Selenium IDE是F ...
- 阶段小项目2:显示bin格式图片
#include<stdlib.h>#include<stdio.h>#include<string.h>#include<error.h>#inclu ...
- 编写一个js函数,该函数有一个n(数字类型),其返回值是一个数组,该数组内是n个随机且不重复的整数,且整数取值范围是[2,32]
首先定义个fn用来返回整数的取值范围: function getRand(a,b){ var rand = Math.ceil(Math.random()*(b-a)+a); return rand; ...
- Kaggle新手入门之路
学完了Coursera上Andrew Ng的Machine Learning后,迫不及待地想去参加一场Kaggle的比赛,却发现从理论到实践的转变实在是太困难了,在此记录学习过程. 一:安装Anaco ...
- Qt Creator 整合 python 解释器教程
目录 1. 前言 2.前提条件 3.步骤 3.1 新建 python文件 3.2 编写 python 代码 3.3 配置 python 解释器 3.4 执行 python file 1. 前言 Pyt ...
- Day5模块-shutil模块
参考博客:http://www.cnblogs.com/wupeiqi/articles/4963027.html shutil模块是高级的文件.文件夹.压缩处理的模块.比如文件的copy.压缩等. ...
- linux 运维 nginx服务器
nginx(web服务器) nginx是一个高性能的http和反向代理服务器,同时也是一个imap/pop3/smtp 代理服务器比apache简单官网:http://nginx.org nginx配 ...
- (28000): Access denied for user 'root'@'127.0.0.1' (using password: YES)
在一台测试服务器测试Python脚本时,执行Python脚本时报如下错误: 主要错误信息为"operation the sql fail!1045 (28000): Access den ...
- 笔记︱集成学习Ensemble Learning与树模型、Bagging 和 Boosting
本杂记摘录自文章<开发 | 为什么说集成学习模型是金融风控新的杀手锏?> 基本内容与分类见上述思维导图. . . 一.机器学习元算法 随机森林:决策树+bagging=随机森林 梯度提升树 ...