<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:task="http://www.springframework.org/schema/task"
xmlns:rabbit="http://www.springframework.org/schema/rabbit"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task.xsd
http://www.springframework.org/schema/rabbit
http://www.springframework.org/schema/rabbit/spring-rabbit-1.7.xsd"> <description>rabbitmq 连接服务配置</description>
<!-- 不适用【发布确认】连接配置 -->
<rabbit:connection-factory id="rabbitConnectionFactory"
host="172.18.112.102" username="woms" password="woms" port="5672"
virtual-host="lingyi" channel-cache-size="25" cache-mode="CHANNEL" publisher-confirms="true" publisher-returns="true" connection-timeout="200"/> <bean id="retryTemplate" class="org.springframework.retry.support.RetryTemplate">
<property name="backOffPolicy">
<bean class="org.springframework.retry.backoff.ExponentialBackOffPolicy">
<property name="initialInterval" value="200" />
<property name="maxInterval" value="30000" />
</bean>
</property>
<property name="retryPolicy">
<bean class="org.springframework.retry.policy.SimpleRetryPolicy">
<property name="maxAttempts" value="5"/>
</bean>
</property>
</bean> <!--通过指定下面的admin信息,当前producer中的exchange和queue会在rabbitmq服务器上自动生成 如果使用多exchange必须配置declared-by="connectAdmin" -->
<rabbit:admin id="connectAdmin" connection-factory="connectionFactory"/> <rabbit:template id="ampqTemplate" connection-factory="connectionFactory"
exchange="test-mq-exchange" return-callback="sendReturnCallback"
message-converter="jsonMessageConverter" routing-key="test_queue_key"
mandatory="true" confirm-callback="confirmCallback" retry-template="retryTemplate"/> <bean id="confirmCallback" class="ly.net.rabbitmq.MsgSendConfirmCallBack" />
<bean id="sendReturnCallback" class="ly.net.rabbitmq.MsgSendReturnCallback" />
<!-- 消息对象json转换类 -->
<bean id="jsonMessageConverter" class="org.springframework.amqp.support.converter.Jackson2JsonMessageConverter" /> <!-- queue配置 -->
<!-- durable:是否持久化 -->
<!-- exclusive: 仅创建者可以使用的私有队列,断开后自动删除 -->
<!-- auto_delete: 当所有消费客户端连接断开后,是否自动删除队列 -->
<rabbit:queue id="test_queue_key" name="test_queue_key" durable="true" auto-delete="false" exclusive="false" declared-by="rabbitAdmin" /> <!-- exchange配置 -->
<!-- rabbit:direct-exchange:定义exchange模式为direct,意思就是消息与一个特定的路由键完全匹配,才会转发。 -->
<!-- rabbit:binding:设置消息queue匹配的key -->
<rabbit:direct-exchange name="test-mq-exchange"
durable="true" auto-delete="false" id="test-mq-exchange" declared-by="rabbitAdmin">
<rabbit:bindings>
<rabbit:binding queue="test_queue_key" key="test_queue_key" />
</rabbit:bindings>
</rabbit:direct-exchange> <!-- <rabbit:topic-exchange name="${mq.queue}_exchange" durable="true" auto-delete="false"> -->
<!-- <rabbit:bindings> -->
<!-- 设置消息Queue匹配的pattern (direct模式为key) -->
<!-- <rabbit:binding queue="test_queue" pattern="${mq.queue}_patt"/> -->
<!-- </rabbit:bindings> -->
<!-- </rabbit:topic-exchange> --> <bean id="mqConsumer" class="ly.net.rabbitmq.MQConsumer" />
<bean id="mqConsumer1" class="ly.net.rabbitmq.MQConsumerManual" /> <!-- listener配置 消费者 自动确认 -->
<!-- queues:监听的队列,多个的话用逗号(,)分隔 ref:监听器 -->
<rabbit:listener-container
connection-factory="connectionFactory" acknowledge="auto"
message-converter="jsonMessageConverter">
<rabbit:listener queues="test_queue_key" ref="mqConsumer" />
</rabbit:listener-container>
<!-- 消费者 手动确认 -->
<rabbit:listener-container
connection-factory="connectionFactory" acknowledge="manual">
<rabbit:listener queues="test_queue_key" ref="mqConsumer1" />
</rabbit:listener-container> </beans>
 package ly.net.rabbitmq;

 import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.support.CorrelationData;
public class MsgSendConfirmCallBack implements RabbitTemplate.ConfirmCallback { @Override
public void confirm(CorrelationData correlationData, boolean ack, String cause) {
// TODO Auto-generated method stub
if (ack) {
System.out.println("消息确认成功");
} else {
//处理丢失的消息
System.out.println("消息确认失败,"+cause);
}
} }
package ly.net.rabbitmq;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.retry.RepublishMessageRecoverer;
import org.springframework.beans.factory.annotation.Autowired; public class MsgSendReturnCallback implements RabbitTemplate.ReturnCallback{
@Autowired
private RabbitTemplate errorTemplate; @Override
public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
String msgJson = new String(message.getBody());
System.out.println("Returned Message:"+msgJson); //重新发布
// RepublishMessageRecoverer recoverer = new RepublishMessageRecoverer(errorTemplate,"errorExchange", "errorRoutingKey");
// Throwable cause = new Exception(new Exception("route_fail_and_republish"));
// recoverer.recover(message,cause);
// System.out.println("Returned Message:"+replyText);
//
} }
 package ly.net.rabbitmq;

 import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.ChannelAwareMessageListener; import com.rabbitmq.client.Channel; public class MQConsumerManual implements ChannelAwareMessageListener { @Override
public void onMessage(Message message, Channel channel) throws Exception {
// TODO Auto-generated method stub
//手动确认
channel.basicAck(message.getMessageProperties().getDeliveryTag(), true);
} }
@Service
public class MQProducerImpl implements MQProducer {
@Autowired
private AmqpTemplate amqpTemplate; private final static Logger LOGGER = Logger.getLogger(MQProducerImpl.class);
/*
* convertAndSend:将Java对象转换为消息发送到匹配Key的交换机中Exchange,由于配置了JSON转换,这里是将Java对象转换成JSON字符串的形式。
* 原文:Convert a Java object to an Amqp Message and send it to a default exchange with a specific routing key.
*/
@Override
public void sendDataToQueue(String queueKey, Object object) {
try {
amqpTemplate.convertAndSend(object); } catch (Exception e) {
LOGGER.error(e);
} }
}
public interface MQProducer {
/**
* 发送消息到指定队列
* @param queueKey
* @param object
*/
public void sendDataToQueue(String queueKey, Object object);
}

RabbitMQ整合spring的更多相关文章

  1. 消息中间件——RabbitMQ(九)RabbitMQ整合Spring AMQP实战!(全)

    前言 1. AMQP 核心组件 RabbitAdmin SpringAMQP声明 RabbitTemplate SimpleMessageListenerContainer MessageListen ...

  2. RabbitMQ学习笔记(5)----RabbitMQ整合Spring

    在Spring AMQP项目中Spring也提供了对RabbitMQ的支持,这里在之前学习SpringBoot的时候也整合过,但是今天这里使用的Spring的xml配置来整个rabbit. Sprin ...

  3. Rabbitmq 整合Spring,SpringBoot与Docker

    SpringBootLearning是对Springboot与其他框架学习与研究项目,是根据实际项目的形式对进行配置与处理,欢迎star与fork. [oschina 地址] http://git.o ...

  4. RabbitMQ整合Spring Booot【消费者补偿幂等问题】

    如果消费者 运行时候 报错了 package com.toov5.msg.SMS; import org.springframework.amqp.rabbit.annotation.RabbitHa ...

  5. RabbitMQ整合Spring Booot【消费者应答模式】

    生产者代码不变,消费者: package com.toov5.Consumer; import java.io.IOException; import java.util.concurrent.Tim ...

  6. RabbitMQ整合Spring Booot【点对点模式】

    pom.xml: <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www. ...

  7. RabbitMQ整合Spring Booot【Exchange-Fanout模式】

    pom: <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.o ...

  8. 关于RabbitMQ以及RabbitMQ和Spring的整合

    转自:https://www.cnblogs.com/s648667069/p/6401463.html 基本概念 RabbitMQ是流行的开源消息队列系统,用erlang语言开发.RabbitMQ是 ...

  9. 消息中间件——RabbitMQ(十)RabbitMQ整合SpringBoot实战!(全)

    前言 1. SpringBoot整合配置详解 publisher-confirms,实现一个监听器用于监听Broker端给我们返回的确认请求:RabbitTemplate.ConfirmCallbac ...

随机推荐

  1. leetcode 136 Single Number, 260 Single Number III

    leetcode 136. Single Number Given an array of integers, every element appears twice except for one. ...

  2. 20145105 《Java程序设计》第7周学习总结

    20145105 <Java程序设计>第7周学习总结 教材学习内容总结 第十三章 时间与日期 一.认识时间与日期 (一)时间的度量 格林威治标准时间 世界时 国际原子时 世界协调时 Uni ...

  3. UVa 12661 Funny Car Racing - spfa

    很简单的一道最短路问题.分情况处理赛道的打开和关闭. Code /** * UVa * Problem#12661 * Accepted * Time:50ms */ #include<iost ...

  4. 删除string类型字符串中指定字符串段

    1.实现背景 在插入list行时用邮件的MessageID给对应行命名. 在回复全部邮件时,收件人变为之前收件人中出去“自己”同时加入之前发件人,抄送人还是之前的抄送人,密送人不用管,直接不用带. 在 ...

  5. 卸载vs2017

    卸载enterprise版本 Microsoft.FSharp.SDK.Core卸载失败Package 'Microsoft.FSharp.SDK.Core,version=15.7.20180605 ...

  6. Java之Elasticsearch 增删改查

    <!--ELK --> <dependency> <groupId>org.elasticsearch.client</groupId> <art ...

  7. 【Android实验】线程的使用-计时器

    目录 实验目的 实验要求 实验过程 实验结果 实验代码 实验总结 实验目的 熟悉和掌握Android线程的使用 实验要求 完成一个秒表,具备启停功能,正确使用工作线程完成界面刷新 分析秒表的计时是否准 ...

  8. hdoj上的一题和程序设计第二次作业的拓展-人见人爱a+b

    hdoj上一道有意思的题目,题目: 人见人爱a+b 敲的也蛮快的,大概十分钟左右就AC了.代码如下: 人见人爱a+b #include<stdio.h> int main() { int ...

  9. shell 判断字符串是否为空

    #!/bin/bash a="" if [ -n "$a" ] then echo "-n $a : 字符串长度不为 0" else ech ...

  10. yaml 文件保存

    with open(mpath, "w") as f: yaml.safe_dump(yaml_dict,f,encoding='utf-8', allow_unicode=Tru ...