热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

开发笔记:Springboot整合二集成rabbitmq

篇首语:本文由编程笔记#小编为大家整理,主要介绍了Springboot整合二集成rabbitmq相关的知识,希望对你有一定的参考价值。

篇首语:本文由编程笔记#小编为大家整理,主要介绍了Springboot整合 二 集成 rabbitmq相关的知识,希望对你有一定的参考价值。



1、在application.yml文件中进行RabbitMQ的相关配置
先上代码


spring:
rabbitmq:
host:
192168.21.11
port:
5672
username: guest
password: password
publisher
-confirms: true # 消息发送到交换机确认机制,是否确认回调
  virtual-host: / #默认主机
#自定义参数
defineProps:
 rabbitmq:
  wechat:
   template:
    topic: wxmsg.topic
    queue: wxmsg.queue
    # *表号匹配一个word,#匹配多个word和路径,路径之间通过.隔开
    queue1_pattern: wxmsg.message.exchange.queue.#
    # *表号匹配一个word,#匹配多个word和路径,路径之间通过.隔开
    queue2_pattern: wxmsg.message.exchange.queue.#

 

2. 项目启动配置


       大家可以看到上图中的config包,这里就是相关配置类
下面,就这三个配置类,做下说明:(这里需要大家对RabbitMQ有一定的了解,知道生产者、消费者、消息交换机、队列等)

 

ExchangeConfig    消息交换机配置


package com.space.rabbitmq.config;

import org.springframework.amqp.core.DirectExchange;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
* 消息交换机配置 可以配置多个
*/
@Configuration
public class ExchangeConfig {
    @Value("${defineProps.rabbitmq.wechat.template.topic}")
    private String templateTopic;
    /**
     *   1.定义topic exchange,绑定路由
     *   2.direct交换器相对来说比较简单,匹配规则为:如果路由键匹配,消息就被投送到相关的队列
     *     fanout交换器中没有路由键的概念,他会把消息发送到所有绑定在此交换器上面的队列中。
     *     topic交换器你采用模糊匹配路由键的原则进行转发消息到队列中
     *   3.durable="true" rabbitmq重启的时候不需要创建新的交换机
     *   4.autoDelete:false ,默认不自动删除
     *   5.key: queue在该topic exchange中的key值,当消息符合topic exchange中routing_key规则,
     *   消息将会转发给queue参数指定的消息队列
     */
    public TopicExchange topicExchange(){
        return new TopicExchange(templateTopic, true, false);
    }
}


QueueConfig 队列配置

package com.space.rabbitmq.config;

import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
* 队列配置 可以配置多个队列
*/
@Configuration
public class QueueConfig {

@Bean
public Queue firstQueue() {
/**
durable="true" 持久化 rabbitmq重启的时候不需要创建新的队列
auto-delete 表示消息队列没有在使用时将被自动删除 默认是false
exclusive 表示该消息队列是否只在当前connection生效,默认是false
*/
return new Queue("queue1",true,false,false);
}

@Bean
public Queue secondQueue() {
return new Queue("queue2",true,false,false);
}
}


RabbitMqConfig RabbitMq配置

package com.space.rabbitmq.config;

import com.space.rabbitmq.mqcallback.MsgSendConfirmCallBack;
import org.springframework.amqp.core.AcknowledgeMode;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
* RabbitMq配置
*/
@Configuration
public class RabbitMqConfig {

    @Value("${spring.rabbitmq.host}")
    private String host;
    @Value("${spring.rabbitmq.port}")
    private int port;
    @Value("${spring.rabbitmq.username}")
    private String username;
    @Value("${spring.rabbitmq.password}")
    private String password;
    @Value("${spring.rabbitmq.virtual-host}")
    private String vhost;
    
    @Value("${defineProps.rabbitmq.wechat.template.
queue1_pattern}")
    private String
queue1_pattern;
    @Value("${defineProps.rabbitmq.wechat.template.
queue2_pattern}")
    private String
queue2_pattern;

@Autowired
private QueueConfig queueConfig;
@Autowired
private ExchangeConfig exchangeConfig;

/**
* 连接工厂
*/
@Bean
public ConnectionFactory connectionFactory() {
CachingConnectionFactory cOnnectionFactory= new CachingConnectionFactory(host, port);
connectionFactory.setUsername(username);
connectionFactory.setPassword(password);
connectionFactory.setVirtualHost(vhost);
return connectionFactory;
}

@Bean
public RabbitTemplate rabbitTemplate(){
return new RabbitTemplate(connectionFactory());
}
/**
将消息队列1和交换机进行绑定
*/
@Bean
public Binding binding_one() {
return BindingBuilder.bind(queueConfig.firstQueue()).to(exchangeConfig.topicExchange()).with(queue1_pattern);
}

/**
* 将消息队列2和交换机进行绑定
*/
@Bean
public Binding binding_two() {
return BindingBuilder.bind(queueConfig.secondQueue()).to(exchangeConfig.topicExchange()).with(queue2_pattern);
}

/**
* queue listener 观察 监听模式
* 当有消息到达时会通知监听在对应的队列上的监听对象
* @return
*/
@Bean
public SimpleMessageListenerContainer simpleMessageListenerContainer_one(){
SimpleMessageListenerContainer simpleMessageListenerContainer
= new SimpleMessageListenerContainer(connectionFactory);
simpleMessageListenerContainer.addQueues(queueConfig.firstQueue());
simpleMessageListenerContainer.setExposeListenerChannel(
true);
simpleMessageListenerContainer.setMaxConcurrentConsumers(
5);
simpleMessageListenerContainer.setConcurrentConsumers(
1);
simpleMessageListenerContainer.setAcknowledgeMode(AcknowledgeMode.MANUAL);
//设置确认模式手工确认
simpleMessageListenerContainer.setMessageListener(wechatPushMessageListener());
return simpleMessageListenerContainer;
}
/**
* 配置消费者bean
* @return
*/
@Bean
public WechatPushMessageConsumer wechatPushMessageListener(){
return new WechatPushMessageConsumer(redisUtil, mqMsgExceptionRemote, wechatAppID, wechatAppSecret);
}

/**
* 定义rabbit template用于数据的接收和发送
* @return
*/
@Bean
public RabbitTemplate rabbitTemplate() {
RabbitTemplate template
= new RabbitTemplate(connectionFactory);
/**若使用confirm-callback或return-callback,
* 必须要配置publisherConfirms或publisherReturns为true
* 每个rabbitTemplate只能有一个confirm-callback和return-callback
*/
template.setConfirmCallback(msgSendConfirmCallBack());
//template.setReturnCallback(msgSendReturnCallback());
/**
* 使用return-callback时必须设置mandatory为true,或者在配置中设置mandatory-expression的值为true,
* 可针对每次请求的消息去确定’mandatory’的boolean值,
* 只能在提供’return -callback’时使用,与mandatory互斥
*/
// template.setMandatory(true);
return template;
}

/**
* 消息确认机制
* Confirms给客户端一种轻量级的方式,能够跟踪哪些消息被broker处理,
* 哪些可能因为broker宕掉或者网络失败的情况而重新发布。
* 确认并且保证消息被送达,提供了两种方式:发布确认和事务。(两者不可同时使用)
* 在channel为事务时,不可引入确认模式;同样channel为确认模式下,不可使用事务。
* @return
*/
@Bean
public MsgSendConfirmCallBack msgSendConfirmCallBack(){
return new MsgSendConfirmCallBack();
}

}

 

消息回调


package com.space.rabbitmq.mqcallback;

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.support.CorrelationData;

/**
* 消息发送到交换机确认机制
* @author zhuzhe
* @date 2018/5/25 15:53
* @email 1529949535@qq.com
*/
public class MsgSendConfirmCallBack implements RabbitTemplate.ConfirmCallback {

@Override
public void confirm(CorrelationData correlationData, boolean ack, String cause) {
System.
out.println("MsgSendConfirmCallBack , 回调id:" + correlationData);
if (ack) {
System.
out.println("消息消费成功");
}
else {
System.
out.println("消息消费失败:" + cause+"\\n重新发送");
}
}
}


 


生产者/消息发送者


package com.space.rabbitmq.sender;

import com.space.rabbitmq.config.RabbitMqConfig;
import lombok.
extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.support.CorrelationData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.UUID;

/**
* 消息发送 生产者1
* @author zhuzhe
* @date 2018/5/25 14:28
* @email 1529949535@qq.com
*/
@Slf4j
@Component
public class FirstSender {

@Autowired
private RabbitTemplate rabbitTemplate;

/**
* 发送消息
* @param uuid
* @param message 消息
*/
public void send(String uuid,Object message) {
CorrelationData correlationId
= new CorrelationData(uuid);
rabbitTemplate.convertAndSend(RabbitMqConfig.EXCHANGE, RabbitMqConfig.ROUTINGKEY2,
message, correlationId);
}
}


消费者


方式一(使用注解):
package com.space.rabbitmq.receiver;

import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

/**
* 消息消费者1
* @author zhuzhe
* @date 2018/5/25 17:32
* @email 1529949535@qq.com
*/
@Component
public class FirstConsumer {

@RabbitListener(queues
= {"first-queue","second-queue"}, cOntainerFactory= "rabbitListenerContainerFactory")
public void handleMessage(String message) throws Exception {
// 处理消息
System.out.println("FirstConsumer {} handleMessage :"+message);
}
}


方式二(利用配置):
package com.space.rabbitmq.receiver;

import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

/**
* 消息消费者1
*/public class WechatPushMessageConsumer extends BaseMessageConsumer implements ChannelAwareMessageListener

@Override
public void onMessage(Message message, Channel channel) throws Exception {
      System.out.println("接收到的消息:" + message.getBody());
    }

}

 


消息接收两种方式:

@RabbitListener @RabbitHandler 及 消息序列化

参看资料: https://www.jianshu.com/p/911d987b5f11

测试


package com.space.rabbitmq.controller;

import com.space.rabbitmq.sender.FirstSender;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;

/**
* @author zhuzhe
* @date 2018/5/25 16:00
* @email 1529949535@qq.com
*/
@RestController
public class SendController {

@Autowired
private FirstSender firstSender;

@GetMapping(
"/send")
public String send(String message){
String uuid
= UUID.randomUUID().toString();
firstSender.send(uuid,message);
return uuid;
}
}

 

 

 

 

 

 

 

 

package com.space.rabbitmq.controller;
 
import com.space.rabbitmq.sender.FirstSender;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
 
import java.util.UUID;
 
/**
 * @author zhuzhe
 * @date 2018/5/25 16:00
 * @email 1529949535@qq.com
 */
@RestController
public class SendController {
 
    @Autowired
    private FirstSender firstSender;
 
    @GetMapping("/send")
    public String send(String message){
        String uuid = UUID.randomUUID().toString();
        firstSender.send(uuid,message);
        return uuid;
    }
}

topicExchange


推荐阅读
  • 重入锁(ReentrantLock)学习及实现原理
    本文介绍了重入锁(ReentrantLock)的学习及实现原理。在学习synchronized的基础上,重入锁提供了更多的灵活性和功能。文章详细介绍了重入锁的特性、使用方法和实现原理,并提供了类图和测试代码供读者参考。重入锁支持重入和公平与非公平两种实现方式,通过对比和分析,读者可以更好地理解和应用重入锁。 ... [详细]
  • 本文分享了一个关于在C#中使用异步代码的问题,作者在控制台中运行时代码正常工作,但在Windows窗体中却无法正常工作。作者尝试搜索局域网上的主机,但在窗体中计数器没有减少。文章提供了相关的代码和解决思路。 ... [详细]
  • 2021最新总结网易/腾讯/CVTE/字节面经分享(附答案解析)
    本文分享作者在2021年面试网易、腾讯、CVTE和字节等大型互联网企业的经历和问题,包括稳定性设计、数据库优化、分布式锁的设计等内容。同时提供了大厂最新面试真题笔记,并附带答案解析。 ... [详细]
  • 本文介绍了Python高级网络编程及TCP/IP协议簇的OSI七层模型。首先简单介绍了七层模型的各层及其封装解封装过程。然后讨论了程序开发中涉及到的网络通信内容,主要包括TCP协议、UDP协议和IPV4协议。最后还介绍了socket编程、聊天socket实现、远程执行命令、上传文件、socketserver及其源码分析等相关内容。 ... [详细]
  • 本文介绍了Oracle数据库中tnsnames.ora文件的作用和配置方法。tnsnames.ora文件在数据库启动过程中会被读取,用于解析LOCAL_LISTENER,并且与侦听无关。文章还提供了配置LOCAL_LISTENER和1522端口的示例,并展示了listener.ora文件的内容。 ... [详细]
  • Spring特性实现接口多类的动态调用详解
    本文详细介绍了如何使用Spring特性实现接口多类的动态调用。通过对Spring IoC容器的基础类BeanFactory和ApplicationContext的介绍,以及getBeansOfType方法的应用,解决了在实际工作中遇到的接口及多个实现类的问题。同时,文章还提到了SPI使用的不便之处,并介绍了借助ApplicationContext实现需求的方法。阅读本文,你将了解到Spring特性的实现原理和实际应用方式。 ... [详细]
  • 本文介绍了如何使用C#制作Java+Mysql+Tomcat环境安装程序,实现一键式安装。通过将JDK、Mysql、Tomcat三者制作成一个安装包,解决了客户在安装软件时的复杂配置和繁琐问题,便于管理软件版本和系统集成。具体步骤包括配置JDK环境变量和安装Mysql服务,其中使用了MySQL Server 5.5社区版和my.ini文件。安装方法为通过命令行将目录转到mysql的bin目录下,执行mysqld --install MySQL5命令。 ... [详细]
  • 本文介绍了Python爬虫技术基础篇面向对象高级编程(中)中的多重继承概念。通过继承,子类可以扩展父类的功能。文章以动物类层次的设计为例,讨论了按照不同分类方式设计类层次的复杂性和多重继承的优势。最后给出了哺乳动物和鸟类的设计示例,以及能跑、能飞、宠物类和非宠物类的增加对类数量的影响。 ... [详细]
  • 本文介绍了Sencha Touch的学习使用心得,主要包括搭建项目框架的过程。作者强调了使用MVC模式的重要性,并提供了一个干净的引用示例。文章还介绍了Index.html页面的作用,以及如何通过链接样式表来改变全局风格。 ... [详细]
  • 本文讨论了微软的STL容器类是否线程安全。根据MSDN的回答,STL容器类包括vector、deque、list、queue、stack、priority_queue、valarray、map、hash_map、multimap、hash_multimap、set、hash_set、multiset、hash_multiset、basic_string和bitset。对于单个对象来说,多个线程同时读取是安全的。但如果一个线程正在写入一个对象,那么所有的读写操作都需要进行同步。 ... [详细]
  • 本文介绍了在Android开发中使用软引用和弱引用的应用。如果一个对象只具有软引用,那么只有在内存不够的情况下才会被回收,可以用来实现内存敏感的高速缓存;而如果一个对象只具有弱引用,不管内存是否足够,都会被垃圾回收器回收。软引用和弱引用还可以与引用队列联合使用,当被引用的对象被回收时,会将引用加入到关联的引用队列中。软引用和弱引用的根本区别在于生命周期的长短,弱引用的对象可能随时被回收,而软引用的对象只有在内存不够时才会被回收。 ... [详细]
  • AFNetwork框架(零)使用NSURLSession进行网络请求
    本文介绍了AFNetwork框架中使用NSURLSession进行网络请求的方法,包括NSURLSession的配置、请求的创建和执行等步骤。同时还介绍了NSURLSessionDelegate和NSURLSessionConfiguration的相关内容。通过本文可以了解到AFNetwork框架中使用NSURLSession进行网络请求的基本流程和注意事项。 ... [详细]
  • java线程池的实现原理源码分析
    这篇文章主要介绍“java线程池的实现原理源码分析”,在日常操作中,相信很多人在java线程池的实现原理源码分析问题上存在疑惑,小编查阅了各式资 ... [详细]
  • 校园表白墙微信小程序,校园小情书、告白墙、论坛,大学表白墙搭建教程
    小程序的名字必须和你微信注册的名称一模一样在后台注册好小程序。mp.wx-union.cn后台域名https。mp.wx-union.cn ... [详细]
  • rabbitmq杂谈
    rabbitmq中的consumerTag和deliveryTag分别是干啥的,有什么用?同一个会话,consumerTag是固定的可以做此会话的名字,deliveryTag每次接 ... [详细]
author-avatar
黄燕2602917715_290
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有