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

spring:
rabbitmq:
host: 192168.21.11
port:
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();
simpleMessageListenerContainer.setConcurrentConsumers();
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

Springboot整合二 集成 rabbitmq的更多相关文章

  1. springboot整合logback集成elk实现日志的汇总、分析、统计和检索功能

    在Spring Boot当中,默认使用logback进行log操作.logback支持将日志数据通过提供IP地址.端口号,以Socket的方式远程发送.在Spring Boot中,通常使用logbac ...

  2. 如何通过SpringBoot官方手册集成RabbitMQ

    众所周知,SpringBoot是对Spring的一层封装,用来简化操作. 随着SpringBoot的越发成熟,很多的流行技术都提供了SpringBoot的版本. 可以点击下方的连接查看spring-b ...

  3. SpringBoot整合多个RabbitMQ

    一.背景 ​ 最近项目中需要用到了RabbitMQ来监听消息队列,监听的消息队列的 虚拟主机(virtualHost)和队列名(queueName)是不一致的,但是接收到的消息格式相同的.而且可能还存 ...

  4. 【转载】Springboot整合 一 集成 redis

    原文:http://www.ityouknow.com/springboot/2016/03/06/spring-boot-redis.html https://blog.csdn.net/plei_ ...

  5. SpringBoot集成rabbitmq(二)

    前言 在使用rabbitmq时,我们可以通过消息持久化来解决服务器因异常崩溃而造成的消息丢失.除此之外,我们还会遇到一个问题,当消息生产者发消息发送出去后,消息到底有没有正确到达服务器呢?如果不进行特 ...

  6. 一篇学习完rabbitmq基础知识,springboot整合rabbitmq

    一   rabbitmq 介绍 MQ全称为Message Queue,即消息队列, RabbitMQ是由erlang语言开发,基于AMQP(Advanced MessageQueue 高级消息队列协议 ...

  7. springboot集成rabbitmq(实战)

    RabbitMQ简介RabbitMQ使用Erlang语言开发的开源消息队列系统,基于AMQP协议来实现(AMQP的主要特征是面向消息.队列.路由.可靠性.安全).支持多种客户端,如:Python.Ru ...

  8. RabbitMQ与SpringBoot整合

    RabbitMQ  SpringBoot  一.RabbitMQ的介绍 二.Direct模式 三.Topic转发模式 四.Fanout Exchange形式 原文地址: https://www.cnb ...

  9. springboot学习笔记-6 springboot整合RabbitMQ

    一 RabbitMQ的介绍 RabbitMQ是消息中间件的一种,消息中间件即分布式系统中完成消息的发送和接收的基础软件.这些软件有很多,包括ActiveMQ(apache公司的),RocketMQ(阿 ...

随机推荐

  1. mysql数据库操作语句整合

    查看版本:select version();显示当前时间:select now(); 注意:在语句结尾要使用分号; 远程连接 一般在公司开发中,可能会将数据库统一搭建在一台服务器上,所有开发人员共用一 ...

  2. ContextRefreshedEvent事件使用注意事项(Spring)

    0 概述ContextRefreshedEvent 事件会在Spring容器初始化完成会触发该事件.我们在实际工作也可以能会监听该事件去做一些事情,但是有时候使用不当也会带来一些问题. 1 防止重复触 ...

  3. BZOJ.3227.[SDOI2008]红黑树tree(树形DP 思路)

    BZOJ orz MilkyWay天天做sxt! 首先可以树形DP:\(f[i][j][0/1]\)表示\(i\)个点的子树中,黑高度为\(j\),根节点为红/黑节点的最小红节点数(最大同理). 转移 ...

  4. Scrapy基础(十)———同步机制将Item中的数据写在Mysql

      前面讲解到将Item中的所有字段都已经填写完成,那么接下来就是将他们存储到mysql数据库中,那就用到了pipeline项目管道了:  对项目管道的理解:做一个比喻,爬取好比是开采石油,Item装 ...

  5. 考前停课集训 Day7 嘞

    Day7 正如一个大佬提醒的那样,棕名是会被嘲讽的 果然…… 在洛谷里…… 算了. 不必在意. 马上就要退役了. NOIP,开始的地方,也是结束的地方. 如果一群OIer比你小 还会嘲讽你, 你就该退 ...

  6. 11-13 js操作css样式

    1.Js操作css样式 Div.style.width=”100px”.在div标签内我们添加了一个style属性,并设定了width值.这种写法会给标签带来大量的style属性,跟实际项目是不符. ...

  7. oracle数据库启动和关闭方式

    Oracle数据库是重量级的,其管理非常复杂,将其在Linux平台上的启动和关闭步骤整理一下. 安装完毕oracle以后,需要创建oracle系统用户,并在/home/oracle下面的.bash_p ...

  8. js 事件冒泡、捕获;call()、apply()

    他们是描述事件触发时序问题的术语.事件捕获指的是从document到触发事件的那个节点,即自上而下的去触发事件.相反的,事件冒泡是自下而上的去触发事件.绑定事件方法的第三个参数,就是控制事件触发顺序是 ...

  9. Node_初步了解(4)小爬虫

    var http=require('http'); var cheerio=require('cheerio'); var url='http://www.cnblogs.com/Lwd-linux/ ...

  10. C#静态代码检查工具StyleCode

    C#静态代码检查工具StyleCode -- 初探 最近我们Advent Data Service (ADS) 在项目上需要按照代码规范进行代码的编写工作,以方便将来代码的阅读与维护. 但是人工检查起 ...