Spring boot (3) 整合RabbitMQ

RabbitMQ是我们常用的消息中间件,这一章节将会在spring boot中集成RabbitMQ。RabbitMQ有四种Exchange模式Direct、Topic、Fanout和Header,常用的是前三种。

Mac系统下安装RabbitMQ可以【参考这里】。

1. 新建springboot项目spring-boot-rabbitmq,在pom.xml中添加RabbitMQ的依赖

<dependency>
	<groupId>org.springframework.amqp</groupId>
	<artifactId>spring-rabbit</artifactId>
	<exclusions>
		<exclusion>
			<artifactId>log4j</artifactId>
			<groupId>log4j</groupId>
		</exclusion>
	</exclusions>
</dependency>

2. 在application.properties中配置RabbitMQ相关信息

spring.rabbitmq.addresses=localhost:5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest

3. Direct Exchange交换机

这是RabbitMQ默认的交换机模式,发送到该交换机的消息都会被转发到RouteKey中指定的Queue中,也就是点对点模式。

3.1 建立名称为 hello.queue 的队列。

@Configuration
public class MQDirectConfig {

	@Bean
	public Queue helloQueue() { 
		return new Queue(MQConstants.HELLO_QUEUE, true);
	}
}

3.2 建立 SenderController.java 模拟生产者。

@RestController
public class SenderController {

	@Autowired
	private RabbitTemplate rabbitTemplate;
	
	@GetMapping("/direct")
	public String direct(String message) {
		System.err.println("发送direct消息: " + message);
		rabbitTemplate.convertAndSend(MQConstants.HELLO_QUEUE, message);
		return "success";
	}
}

我们使用Spring封装好的工具类RabbitTemplate来发送消息。

3.3 新建 MQListener.java 来监听消息

@Component
public class MQListener {

	/**
	 * 
	 * Direct 消息消费者
	 * 
	 * @param message
	 */
	@RabbitListener(queues = MQConstants.HELLO_QUEUE)
	public void direct(Message message) {
		try {
			String body = new String(message.getBody(), "UTF-8");
			System.err.println("收到direct消息: " + body);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}
}

3.4 测试,启动我们的spring boot 项目,在浏览器输入 http://localhost:8080/direct?message=helloword , 在控制台中可以看到以下结果,说明我们向direct交换机发送消息成功,并且消费者也能正常消费消息。

4. Fanout Exchange交换机

所有发送到Fanout Exchange交换机的消息,都会被转发到与这个Exchange绑定(Binding)的所有Queue上,也就是发布/订阅模式,或者广播模式,这种模式不需要RouteKey。

4.1 建立一个名称为 hello.fanout.exchange 的Fanout Exchange交换机

@Configuration
public class MQFanoutConfig {
    @Bean
    public FanoutExchange exchange(){
        return new FanoutExchange(MQConstants.HELLO_FANOUT_EXCHANGE);
    }
}

4.2 在生产者 SenderController.java 添加fanout消息发送者

@GetMapping("/fanout")
public String fanout(String message) {
	System.err.println("发送fanout消息: " + message);
	rabbitTemplate.convertAndSend(MQConstants.HELLO_FANOUT_EXCHANGE, null, message);
	return "success";
}

向 hello.fanout.exchange 交换机中发送Fanout消息,RouteKey是null表示不需要绑定。

4.3 在MQListener.java中 新建两个Queue与该交换机绑定。

	
	/**
	 * 
	 * Fanout消息,消费者A
	 *
	 * @param message
	 */
	@RabbitListener(bindings = {@QueueBinding(value = @Queue(value = "fanout.hello.queue.a", durable = "true"),
            exchange = @Exchange(type=ExchangeTypes.FANOUT, value = MQConstants.HELLO_FANOUT_EXCHANGE))})
	public void fanoutA(Message message) {
		try {
			String body = new String(message.getBody(), "UTF-8");
			System.err.println("A-收到fanout消息: " + body);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 
	 * Fanout消息,消费者B
	 *
	 * @param message
	 */
	@RabbitListener(bindings = {@QueueBinding(value = @Queue(value = "fanout.hello.queue.b", durable = "true"),
            exchange = @Exchange(type=ExchangeTypes.FANOUT, value = MQConstants.HELLO_FANOUT_EXCHANGE))})
	public void fanoutB(Message message) {
		try {
			String body = new String(message.getBody(), "UTF-8");
			System.err.println("B-收到fanout消息: " + body);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}

4.4 测试。启动项目,在浏览器中输入 http://localhost:8080/fanout?message=helloword , 可以看到控制台输出的结果,两个与hello.fanout.exchange绑定的Queue都收到了这条消息。

5. Topic Exchange交换机

与Direct模式的原理一样,都根据路由键进行消息的路由,这种模式支持路由键的模糊匹配,队列需要绑定要一个模式上。符号“#”匹配一个或多个词,符号“*”匹配仅一个词。

5.1 建立一个TopicExchange交换机

@Configuration
public class MQTopicConfig {
    @Bean
    public TopicExchange helloTopicExchange() {
        return new TopicExchange(MQConstants.HELLO_TOPIC_EXCHANGE);
    }
}

5.2 在生产者SenderController中添加代码,发送4个topic消息

@GetMapping("/topic")
public String topic(String message) {
	System.err.println("发送topic消息: " + message);
	rabbitTemplate.convertAndSend(MQConstants.HELLO_TOPIC_EXCHANGE, "topic.cn.news", "topic.cn.news-" + message);
	rabbitTemplate.convertAndSend(MQConstants.HELLO_TOPIC_EXCHANGE, "topic.hk.news", "topic.hk.news-" + message);
	rabbitTemplate.convertAndSend(MQConstants.HELLO_TOPIC_EXCHANGE, "topic.cn.sports", "topic.cn.sports-" + message);
	rabbitTemplate.convertAndSend(MQConstants.HELLO_TOPIC_EXCHANGE, "topic.hk.sports", "topic.hk.sports-" + message);
	return "success";
}

5.3 在消费者MQListener中建立两个队列,分别监听topic.cn.开头和.news结尾的消息。

	/**
	 * 
	 * Topic消息,topic.cn.#
	 *
	 * @param message
	 */
	@RabbitListener(bindings = {@QueueBinding(value = @Queue(value = "topic.cn.#", durable = "true"),
			exchange = @Exchange(type=ExchangeTypes.TOPIC, value = MQConstants.HELLO_TOPIC_EXCHANGE), key = "topic.cn.#")})
	public void topicCn(Message message) {
		try {
			String body = new String(message.getBody(), "UTF-8");
			System.err.println("Topic消息,topic.cn.#-收到消息: " + body);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 
	 * Topic消息,#.news
	 *
	 * @param message
	 */
	@RabbitListener(bindings = {@QueueBinding(value = @Queue(value = "#.news", durable = "true"),
			exchange = @Exchange(type=ExchangeTypes.TOPIC, value = MQConstants.HELLO_TOPIC_EXCHANGE), key = "#.news")})
	public void news(Message message) {
		try {
			String body = new String(message.getBody(), "UTF-8");
			System.err.println("Topic消息,#.news-收到消息: " + body);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}

5.4 测试。在浏览器中输入 http://localhost:8080/topic?message=helloword, 可以在控制台中看到以下结果。

我们可以看到,监听 #.new 的队列消费了topic.cn.news-helloword 和 topic.hk.news-helloword两条消息,

监听 topic.cn.# 的队列消费了topic.cn.news-helloword 和 topic.cn.sports-helloword 两条消息。

github源码 https://github.com/johnwongz/spring-boot-demo

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值