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 的服务通常是架构层面上的考虑. 因为它天生就具有很好的跨平台跨语言的集成能力 ...
随机推荐
- GitHub入门与实践
基本命令 git status 工作区状态 git add git commint 暂存区 git push gitHub客户端 下载网址:https://desktop.github.com/ 解决 ...
- Mac系统下XAMPP的简单使用
XAMPP简单使用的方法使用方法 XAMPP的简介即应用在博客园也有 1.安装完成后打开manager-osx.app 把Manager Servers下的三个server打开(使之变绿如下) 第一个 ...
- 关于echarts 报错 初始化对象未定义
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title&g ...
- 【Unity3D技术文档翻译】第1.3篇 创建 AssetBundles
上一章:[Unity3D技术文档翻译]第1.2篇 为打包 AssetBundles 准备资产 本章原文所在章节:[Unity Manual]→[Working in Unity]→[Advanced ...
- 单元测试——Qunit
为什么需要单元测试 正确性:测试可以验证代码的正确性,在上线前做到心里有底 自动化:当然手工也可以测试,通过console可以打印出内部信息,但是这是一次性的事情,下次测试还需要从头来过,效率不能得到 ...
- 一个简单清晰的Redis操作类
<?php /** * redis处理的二次封装 * */ class Redis{ private $_redis; private $_config; public function __c ...
- Shell脚本的基本流程控制
if else read -p '请输入分数:' score if [ $score -lt 60 ]; then echo '60分以下' elif [ $score -lt 70 ]; then ...
- 1014. Waiting in Line (模拟)
n个窗口就有n个队列,模拟这n个队列就可以了.需要注意的是,一个人在选择排队窗口的时候,他会选择排队人数最少的窗口,如果存在多个窗口排队的人数相同,那么他会选择编码最小的窗口. Note that s ...
- hihoCoder1310 岛屿 (dfs)
思路:首先dfs求得所有联通块,再搜索的同时把每个联通块的坐标都保存下来,然后把每个联通块处理一下–首先得到某个联通块的最小横坐标和纵坐标,然后让每个坐标去减去这个横坐标和纵坐标.相当于使得所有联通块 ...
- WC2016自测
挑战NPC 原题链接 爆搜20分,贪心10分,网络流30分 //挑战NPC #include <cstdio> #include <cstring> #include < ...