springboot整合ribbitMQ
参考:https://blog.csdn.net/a13627210064/article/details/82348059
参考:https://blog.csdn.net/u010288264/article/details/55260237 (1 2 3 4)
依賴:
<repositories><!-- 代码库 -->
<repository>
<id>maven-ali</id>
<url>http://maven.aliyun.com/nexus/content/groups/public//</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
<updatePolicy>always</updatePolicy>
<checksumPolicy>fail</checksumPolicy>
</snapshots>
</repository>
</repositories> <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency> <!-- <dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bus-amqp</artifactId>
</dependency> --> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency> <dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency> </dependencies>
yml 配置连接
spring:
rabbitmq:
# host: 192.168.18.129
addresses: 192.168.18.129:
username: guest
password: guest
# 支持发布确认
publisher-confirms: true
# 支持发布返回
publisher-returns: true
listener:
simple:
# 监听的最小线程数
concurrency:
# 监听的最大线程数
max-concurrency:
retry:
enabled: true
# ack应答改模式:auto-自动,manual-手动,none-无应答
acknowledge-mode: auto
生产者:发送消息
方式一:derict
配置:
package com.icil.config; import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.QueueBuilder;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; //@Configuration
public class RabbitConfig {
/********************************direct****************************************/
// 交换机定义,这里我使用的是direct类型。大家可以根据自己的业务需求来指定对应的。下面会讲几种交换机的类型
// 对应的3个参数1.交换机名称 2.持久性保持标识 3.是否自动删除标识
@Bean
public DirectExchange directExchange() {
return new DirectExchange("name", false, false);
} //创建一个队列
@Bean(name = "queue")
public Queue queue() {
return QueueBuilder.durable("name").build();
} //绑定队列到交换机上--with对应的是direct指定的具体key。
@Bean
public Binding binding(@Qualifier("queue") Queue queue,@Qualifier("directExchange") DirectExchange exchange) {
return BindingBuilder.bind(queue).to(exchange).with("key"); } //
// /********************************topic****************************************/
//
//
// @Bean
// public TopicExchange topicExchange() {
// /**
// * TopicExchangeName
// * 是否持久化
// * 是否自动删除
// */
// return new TopicExchange("topicExchange", true, false);
// }
//
// /**
// * 创建一个队列,指定一个Exchange
// * @return
// */
// @Bean(name = "topicQueue")
// public Queue topicQueue() {
// return QueueBuilder.durable("topicExchange").build();
// }
//
//
// @Bean
// public Binding bindingtopic(@Qualifier("topicQueue") Queue queue, DirectExchange exchange) {
// return BindingBuilder.bind(queue).to(exchange).with("A.B.C"); } }
发送消息:
package com.icil.rabbitmq; import javax.annotation.PostConstruct; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.core.RabbitTemplate.ConfirmCallback;
import org.springframework.amqp.rabbit.core.RabbitTemplate.ReturnCallback;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; import lombok.extern.slf4j.Slf4j;
@Component
@Slf4j
public class RabbitProducer implements ConfirmCallback , ReturnCallback{ private static Logger log =LoggerFactory.getLogger(RabbitProducer.class); @Autowired
private RabbitTemplate rabbitTemplate; /** * 初始化确认发送回调及发送返回回调 */
@PostConstruct
public void init(){
rabbitTemplate.setConfirmCallback(this);
rabbitTemplate.setReturnCallback(this);
} /**
* 实现消息发送到RabbitMQ交换器后接收ack回调
* @param correlationData
* @param ack
* @param cause
*/
@Override
public void confirm(CorrelationData correlationData, boolean ack, String cause) { if (ack){
// 发送成功
log.info("trainLink message send success ---"+System.currentTimeMillis() );
} else { // 发送失败
log.error("trainLink message send failed because ---" + cause);
}
} /**
* * 实现消息发送到RabbitMQ交换器,但无相应队列与交换器绑定时的回调
* * @param message
* * @param replyCode
* * @param replyText
* * @param exchange
* * @param routingKey
*/
@Override
public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
// log.error(message.getMessageProperties().getCorrelationIdString() + " send failed:error code " + replyCode + "mains:" + replyText);
log.error(message.getMessageProperties().getClusterId() + " send failed:error code " + replyCode + "mains:" + replyText); } /**
* * 发送消息,供外部调用
* * ****** 重要 ******说明:发送时的方法选择
* * ****** 重要 ******convertAndSend属于不要求返回确认的
* * ****** 重要 ******convertSendAndReceive要求返回确认
* * ****** 重要 ******大家根据不同的业务场景进行选择,
* * 不返回确认可以理解为全异步;
* * 返回确认可以理解为异步处理,同步返回,存在一个生产者等待消费者的问题
* * 选择的原则一般为一致性要求较强的,要确认返回;
* * 一致性不强的,使用不返回确认,加大处理效率,免去等待时间 */ public void sendSMSMessage(String msg){
// fanout类型的交换器不需要routingkey,我这里用的是direct所以指定了对应的routingkey
this.rabbitTemplate.convertAndSend("name", "key", msg);
// this.rabbitTemplate.convertSendAndReceive(msg);
// this.rabbitTemplate.converandre
} // public static void main(String[] args) {
// RabbitProducer rabbitProducer = new RabbitProducer();
// rabbitProducer.sendSMSMessage("just for test");
// } }
方式二 : topic
配置:
package com.icil.config; import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.QueueBuilder;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; @Configuration
public class RabbitConfig2 { /********************************topic****************************************/ @Bean
public TopicExchange topicExchange() {
/**
* TopicExchangeName
* 是否持久化
* 是否自动删除
*/
return new TopicExchange("topicExchange", true, false);
} /**
* 创建一个队列,指定一个Exchange
* @return
*/
@Bean
public Queue topicQueue01() {
return QueueBuilder.durable("topicExchange01").build();
} @Bean
public Queue topicQueue02() {
return QueueBuilder.durable("topicExchange02").build();
} @Bean
public Binding binding() {
return BindingBuilder.bind(topicQueue01()).to(topicExchange()).with("A.#");
}
@Bean
public Binding binding2() {
return BindingBuilder.bind(topicQueue02()).to(topicExchange()).with("#.B.#");
} // @Bean
// public Binding bindingtopic(@Qualifier("topicQueue") Queue queue, DirectExchange exchange) {
// return BindingBuilder.bind(queue).to(exchange).with("A.B.C"); } }
发送消息:
package com.icil.rabbitmq; import javax.annotation.PostConstruct; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.core.RabbitTemplate.ConfirmCallback;
import org.springframework.amqp.rabbit.core.RabbitTemplate.ReturnCallback;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; import lombok.extern.slf4j.Slf4j;
@Component
@Slf4j
public class RabbitProducer002 implements ConfirmCallback , ReturnCallback{ private static Logger log =LoggerFactory.getLogger(RabbitProducer002.class); @Autowired
private RabbitTemplate rabbitTemplate; /** * 初始化确认发送回调及发送返回回调 */
@PostConstruct
public void init(){
rabbitTemplate.setConfirmCallback(this);
rabbitTemplate.setReturnCallback(this);
} /**
* 实现消息发送到RabbitMQ交换器后接收ack回调
* @param correlationData
* @param ack
* @param cause
*/
@Override
public void confirm(CorrelationData correlationData, boolean ack, String cause) { if (ack){
// 发送成功
log.info("trainLink message send success################## 888---"+System.currentTimeMillis() ); log.info("cause is################## ---",cause );
} else { // 发送失败
log.error("trainLink message send failed because ---" + cause);
}
} /**
* * 实现消息发送到RabbitMQ交换器,但无相应队列与交换器绑定时的回调
* * @param message
* * @param replyCode
* * @param replyText
* * @param exchange
* * @param routingKey
*/
@Override
public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) { log.info("$$$$$$$$$$$$$$$$$$$$$$$ message is {} $$$ replyCode is {} $$$ replyText is {} $$$ exchange is {} $$$ and routingKey is {}",message,replyCode, replyText,exchange,routingKey);
// log.error(message.getMessageProperties().getCorrelationIdString() + " send failed:error code " + replyCode + "mains:" + replyText);
log.error(message.getMessageProperties().getClusterId() + " send failed:error code " + replyCode + "mains:" + replyText); } /**
* * 发送消息,供外部调用
* * ****** 重要 ******说明:发送时的方法选择
* * ****** 重要 ******convertAndSend属于不要求返回确认的
* * ****** 重要 ******convertSendAndReceive要求返回确认
* * ****** 重要 ******大家根据不同的业务场景进行选择,
* * 不返回确认可以理解为全异步;
* * 返回确认可以理解为异步处理,同步返回,存在一个生产者等待消费者的问题
* * 选择的原则一般为一致性要求较强的,要确认返回;
* * 一致性不强的,使用不返回确认,加大处理效率,免去等待时间 */ public void sendSMSMessage(String msg){
// fanout类型的交换器不需要routingkey,我这里用的是direct所以指定了对应的routingkey
this.rabbitTemplate.convertAndSend("topicExchange", "A.B.key", msg);
} }
/*********************************************************************/
接受消息: (依赖与上面一样,无需其他配置)
配置yml
spring:
rabbitmq:
# host: 192.168.18.129
addresses: 192.168.18.129:
username: root
password: root
# 支持发布确认
publisher-confirms: true
# 支持发布返回
publisher-returns: true
listener:
simple:
# 监听的最小线程数
concurrency:
# 监听的最大线程数
max-concurrency:
retry:
enabled: true
# ack应答改模式:auto-自动,manual-手动,none-无应答
acknowledge-mode: auto
接收消息:(使用注解 --也可不用,此处用注解)
方式一:注解 可以参考 :https://www.jianshu.com/p/382d6f609697
package com.icil.rabbitmq; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component; import com.rabbitmq.client.Channel; @Component
public class RabbitMQConsumer {
private static Logger log =LoggerFactory.getLogger(RabbitMQConsumer.class);
/**
* * 消费者处理接收消息方法 *
* <p>
* * ****重要说明***** * 如果生产者是以convertSendAndReceive方法发送,则一定要手动给予返回,处理完后加入下面这一行: *
* ack-true处理:channel.basicAck(message.getMessageProperties().getDeliveryTag(),
* false); * 参数说明-------消息id,fasle代表不批量处理(批量是指将消息id小于当前id的都处理掉) *
* ack-false处理:channel.basicNack(message.getMessageProperties().getDeliveryTag(),
* false, false); *
* 参数说明-------消息id,fasle代表不批量处理(批量是指将消息id小于当前id的都处理掉),第二个false表示不重新入队(重新入队用true)
* * 拒绝消息:channel.basicReject(message.getMessageProperties().getDeliveryTag(),
* false); 消息不会重新入队 * 参数说明-------消息id,fasle表示不重新入队(重新入队用true) *
* 如果不手动返回,则该消息会一直认为没有被消费掉,会一直占用rabbitmq内存空间,时间一久,必然造成内存溢出,切记!!! * * @param msg
* * @param message * @param channel * @throws Exception
*/ //支持自动声明绑定,声明之后自动监听队列的队列,此时@RabbitListener注解的queue和bindings不能同时指定,否则报错
// @RabbitListener(bindings ={@QueueBinding(value = @Queue(value = "q5",durable = "true"),
// exchange =@Exchange(value = "zhihao.miao.exchange",durable = "true"),key = "welcome")}) // @RabbitListener(queues = "name")
// @RabbitListener(queues = {"name","topicExchange01","topicExchange02"})
// public void handler(String msg, Message message, Channel channel) throws Exception {
// try {
// System.out.println("$$$$$$$$$$$$$$$$$$$$$$"+msg);
// } catch (Exception e) {
// log.error(e.toString(), e);
// channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);
// }
// } @RabbitListener(queues = {"topicExchange01"})
public void handler1(String msg, Message message, Channel channel) throws Exception {
try {
System.out.println("$$$$$$$$$$ topicExchange01 $$$$$$$$$$$$"+msg);
} catch (Exception e) {
log.error(e.toString(), e);
channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);
}
} @RabbitListener(queues = {"topicExchange02"})
public void handler2(String msg, Message message, Channel channel) throws Exception {
try {
System.out.println("$$$$$$$$$$ topicExchange02 $$$$$$$$$$$$"+msg);
} catch (Exception e) {
log.error(e.toString(), e);
channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);
}
} @RabbitListener(queues = {"name"})
public void handler3(String msg, Message message, Channel channel) throws Exception {
try {
System.out.println("$$$$$$$$$$ name $$$$$$$$$$$$"+msg);
} catch (Exception e) {
log.error(e.toString(), e);
channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);
}
} }
方式二: 手动配置
package com.icil.config; import org.springframework.amqp.core.AcknowledgeMode;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.QueueBuilder;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import com.rabbitmq.client.Channel;
@Configuration
public class Rabbitconfing { @Bean
public CachingConnectionFactory connectionFactory(){
CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
connectionFactory.setAddresses("192.168.18.129:5672");
connectionFactory.setUsername("guest");
connectionFactory.setPassword("guest");
connectionFactory.setVirtualHost("/");
connectionFactory.setPublisherConfirms(true); //必须要设置
return connectionFactory;
} @Bean
public TopicExchange topicExchange() {
/**
* TopicExchangeName
* 是否持久化
* 是否自动删除
*/
return new TopicExchange("topicExchange", true, false);
} @Bean
public Queue topicQueue01() {
return QueueBuilder.durable("topicExchange01").build();
} @Bean
public Queue topicQueue02() {
return QueueBuilder.durable("topicExchange02").build();
} // @Bean
// public Binding binding() {
// return BindingBuilder.bind(topicQueue01()).to(topicExchange()).with("A.key");
// }
// @Bean
// public Binding binding2() {
// return BindingBuilder.bind(topicQueue02()).to(topicExchange()).with("B.C");
// }
// @Bean
public SimpleMessageListenerContainer messageContainer() {
SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(connectionFactory()); container.setQueues(topicQueue01());
container.setExposeListenerChannel(true);
container.setMaxConcurrentConsumers();
container.setConcurrentConsumers();
container.setAcknowledgeMode(AcknowledgeMode.AUTO); //设置确认模式手工确认
container.setMessageListener(new ChannelAwareMessageListener() {
@Override
public void onMessage(Message message, Channel channel) throws Exception {
byte[] body = message.getBody();
System.out.println("¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥receive msg queue: " + new String(body));
// Thread.sleep(10000); channel.basicAck(message.getMessageProperties().getDeliveryTag(), false); //确认消息成功消费 } });
return container;
} @Bean
public SimpleMessageListenerContainer messageContainer2() {
SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(connectionFactory());
container.setQueues(topicQueue02());
container.setExposeListenerChannel(true);
container.setMaxConcurrentConsumers();
container.setConcurrentConsumers();
container.setAcknowledgeMode(AcknowledgeMode.MANUAL); //设置确认模式手工确认
container.setMessageListener(new ChannelAwareMessageListener() {
@Override
public void onMessage(Message message, Channel channel) throws Exception {
byte[] body = message.getBody();
System.out.println("¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥key: " + new String(body));
// Thread.sleep(10000);
channel.basicAck(message.getMessageProperties().getDeliveryTag(), false); //确认消息成功消费 }
});
return container;
} }
springboot整合ribbitMQ的更多相关文章
- spring-boot整合mybatis(1)
sprig-boot是一个微服务架构,加快了spring工程快速开发,以及简便了配置.接下来开始spring-boot与mybatis的整合. 1.创建一个maven工程命名为spring-boot- ...
- SpringBoot整合Mybatis之项目结构、数据源
已经有好些日子没有总结了,不是变懒了,而是我一直在奋力学习springboot的路上,现在也算是完成了第一阶段的学习,今天给各位总结总结. 之前在网上找过不少关于springboot的教程,都是一些比 ...
- springboot整合mq接收消息队列
继上篇springboot整合mq发送消息队列 本篇主要在上篇基础上进行activiemq消息队列的接收springboot整合mq发送消息队列 第一步:新建marven项目,配置pom文件 < ...
- springboot整合mybaits注解开发
springboot整合mybaits注解开发时,返回json或者map对象时,如果一个字段的value为空,需要更改springboot的配置文件 mybatis: configuration: c ...
- SpringBoot整合Redis、ApachSolr和SpringSession
SpringBoot整合Redis.ApachSolr和SpringSession 一.简介 SpringBoot自从问世以来,以其方便的配置受到了广大开发者的青睐.它提供了各种starter简化很多 ...
- SpringBoot整合ElasticSearch实现多版本的兼容
前言 在上一篇学习SpringBoot中,整合了Mybatis.Druid和PageHelper并实现了多数据源的操作.本篇主要是介绍和使用目前最火的搜索引擎ElastiSearch,并和Spring ...
- SpringBoot整合Kafka和Storm
前言 本篇文章主要介绍的是SpringBoot整合kafka和storm以及在这过程遇到的一些问题和解决方案. kafka和storm的相关知识 如果你对kafka和storm熟悉的话,这一段可以直接 ...
- SpringBoot整合SpringCloud搭建分布式应用
什么是SpringCloud? SpringCloud是一个分布式的整体解决方案.SpringCloud为开发者提供了在分布式系统中快速构建的工具,使用SpringCloud可以快速的启动服务或构建应 ...
- SpringBoot整合RabbitMQ-整合演示
本系列是学习SpringBoot整合RabbitMQ的练手,包含服务安装,RabbitMQ整合SpringBoot2.x,消息可靠性投递实现等三篇博客. 学习路径:https://www.imooc. ...
随机推荐
- 字符串匹配--扩展KMP模板
对于一个字符串 s 以及子串 t ,扩展KMP可以用来求 t 与 s 的每个子串的最长公共前缀 ext [ i ],当然,如果有某个 ext 值等于 t 串的长度 lent ,那么就说明从其对应的 i ...
- LG2023 [AHOI2009]维护序列
题意 老师交给小可可一个维护数列的任务,现在小可可希望你来帮他完成. 有长为N的数列,不妨设为a1,a2,-,aN .有如下三种操作形式: (1)把数列中的一段数全部乘一个值; (2)把数列中的一段数 ...
- GridControl 之 BandedGridView
https://documentation.devexpress.com/#WindowsForms/clsDevExpressXtraGridViewsBandedGridBandedGridVie ...
- WAJUEJI which home strong!nyoj
WAJUEJI which home strong! 时间限制:1000 ms | 内存限制:65535 KB 难度:2 描述 在一个山沟里,姐弟俩同时考上了大学.但由于家里拮据,所以这并不是 ...
- 常见企业IT支撑【6、跳板机Jumpserver】
Jumpserver是国内一款开源的轻便的跳板机系统,他们的官网:http://www.jumpserver.org/ 使用这款软件意在提高公司内部登录生产环境服务器的便捷性,权限分配细化,以及后台管 ...
- flutter初探
这两天看了下flutter,感觉这两年可能会爆发,所以尝试在mac和win10上面跑了下hello world... 移动技术简介 原生开发 跨平台技术简介 H5+原生(Cordova.Ionic.微 ...
- 从Exchager数据交换到基于trade-off的系统设计
可以使用JDK提供的Exchager类进行同步交换:进行数据交换的双方将互相等待对方,直到双方的数据都准备完毕,才进行交换.Exchager类很少用到,但理解数据交换的时机却十分重要,这是一个基于tr ...
- Find minimum continuous subsequence tags
Given targetList, a list of strings representing the desired tags, and availableTagList, a list of s ...
- linux 下安装doker centeros6.5
通过 cat /proc/version .uname [root@192.168.1.1 ~]# cat /proc/version Linux version 2.6.32-279.el6.x86 ...
- 如何使用HttpClient认证机制
1.服务器认证(Server Authentication)HttpClient处理服务器认证几乎是透明的,仅需要开发人员提供登录信息(login credentials).登录信息保存在HttpSt ...