消息发送、接收简单代码示例

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;@Beanpublic 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());}@Beanpublic RabbitAdmin rabbitAdmin(ConnectionFactory connectionFactory) {return new RabbitAdmin(connectionFactory);}}//消息发送
@Component
public class SystemMqMessageSender {private static final Logger logger = LoggerFactory.getLogger(SystemMqMessageSender.class);@Autowiredprivate AmqpTemplate rabbitTemplate;@Value("${send.exchange.name}")private String exchangeSystem;@Value("${send.queue.name}")private String queueSystem;@Resourceprivate RabbitAdmin rabbitAdmin;public void sendMessage(EventModel eventModel) {String message = JsonUtils.json(eventModel);logger.info("发送消息:{}", message);rabbitTemplate.convertAndSend(exchangeSystem, queueSystem, message);}//声明持久化队列,并绑定到exchange上@Beanpublic 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;@RabbitHandlerpublic 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会将消息重新发送给其他监听在队列的下一个消费者。

转载于:https://www.cnblogs.com/canmeng-cn/p/8543113.html

rabbitmq简单收发服务搭建相关推荐

  1. 自玩树莓派记录-关于树莓派LCD3.5英寸屏幕使用及raspios(raspbian)-lite简单GUI服务搭建记录

    自玩树莓派记录-关于树莓派LCD3.5英寸屏幕使用及raspios(raspbian)-lite简单GUI服务搭建记录 硬件准备 1.下载系统 2.树莓派安装系统 上脸 安装GUI服务 最后填个坑,慢 ...

  2. 模拟简单FTP服务搭建--本地用户访问

    文章目录 本地FTP服务(centos7 1511的镜像文件) 一:配置网络等基本配置,挂载镜像,配置本地yum文件,安装vsftpd服务 二:创建普通用户,新建ftp服务可以访问的文件路径(重点) ...

  3. 测试开发——搭建一个简单 web服务(flask框架基础)项目实战

    搭建一个简单 web服务-flask框架 一.什么是wsgi? 二.搭建一个简单 web服务 三.扩展 四.请求加参数的情况 五.安装flask 一.什么是wsgi? wsgi是webserver和a ...

  4. 搭建简单Django服务并通过HttpRequester实现GET/POST http请求提交表单

    调试Django框架写的服务时,需要模拟客户端发送POST请求,然而浏览器只能模拟简单的GET请求(将参数写在url内),网上搜索得到了HttpRequester这一firefox插件,完美的实现了模 ...

  5. 构建自己的简单微服务架构(开源)

    构建自己的简单微服务架构(开源) 原文:构建自己的简单微服务架构(开源) 前言 本篇仅作引导,内容较多,如果阅读不方便,可以使用电脑打开我们的文档官网进行阅读.如下图所示: 文档官网地址:https: ...

  6. PaaS 以及全套服务微服务搭建流程

    这是一篇写的很早的文章,所以有个别内容没那么新,涵盖的内容非常的全,内容太多,可以用于参考. 主要流程分为: Rancher PaaS 平台 MySQL 安装.配置.数据导入 RabbitMQ 安装. ...

  7. CentOS -OpenStack-pike 服务搭建

    Centos-7 部署openstack-pike步骤详解 加入老张: 作者老张 关注老张微信公众号: 一.        环境准备: 控制节点与计算节点都做环境部署 1.1   两台虚拟机 两台ce ...

  8. Apache简单配置(4)搭建Discuz 7.0.0论坛

    Apache简单配置(4)搭建Discuz 7.0.0论坛 RHEL5.3 基本网络配置 一. 1.RHEL5 U3:如图1 (如图1) 2.#hostname //查看当前主机的主机名:如图2 (如 ...

  9. sftp进入指定目录_CentOS7服务搭建----搭建SFTP(安全文件传送协议)服务器

    SFTP协议服务器 简介: sftp是Secure File Transfer Protocol的缩写,安全文件传送协议.可以为传输文件提供一种安全的加密方法.sftp 与 ftp有着几乎一样的语法和 ...

最新文章

  1. JavaScript中的字符串操作(转)
  2. 一个秒杀系统的设计思考
  3. stmmac 中断处理
  4. linux LyX中文编辑环境安装配置指南-TeX可视化工具
  5. 第四十九期:化繁为简的五种码农必备工具
  6. oracle介质恢复的内部过程--推断与参考
  7. luks:Linux Unified Key Setup 持久加密USB
  8. python根据年月日计算天数_「每日一练」Python实现输入年月日计算第几天
  9. JavaScript学习(九十二)—关联数组的基本操作
  10. Oracle增加自增长列
  11. 7-3 小L的难题 (15 分)
  12. PPT(PowerPoint)更改默认等线字体
  13. 对话AI一线大咖,零基础入门Python机器学习与深度学习
  14. 信号与系统实验二___MATLAB
  15. 数据库sql语句关键词大全(适合老人),基本你能知道这几个关键词,基本就知道该如何写了(超简略)
  16. 淘宝平台搜索规则变化,怎么提升搜算转换率?
  17. asp.net饭店点菜管理
  18. c语言字符怎么运算,c语言运算符号(c语言如何输入运算符号)
  19. 关于overflow适配IE的问题
  20. 【Java】什么是二方库?

热门文章

  1. C#double转化成字符串 保留小数位数, 不以科学计数法的形式出现。
  2. 自己动手搭建Nginx+memcache+xdebug+php运行环境绿色版 For windows版
  3. 第二阶段—个人工作总结03
  4. ] ssh登录慢的原因
  5. Scala学习笔记(7)-函数式对象
  6. 把虚拟系统接入网络 虚拟系统工作模式
  7. Linux 浏览网址汇集
  8. Intellectual Property Essentials for Start-Ups
  9. occam‘s razor
  10. ARIA and the value of challenge-led innovation