springboot整合rabbitmq

创建消息生产者微服务

rabbitmq-provider微服务

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.7.2</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.example</groupId>
	<artifactId>rabbitmq-provider</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>rabbitmq-provider</name>
	<description>rabbitmq-provider</description>
	<properties>
		<java.version>1.8</java.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-amqp</artifactId>
			<version>2.3.12.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
			<version>2.3.12.RELEASE</version>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>



</project>

application.yml

server:
  port: 8021

spring:
  application:
    #项目名称
    name: rabbitmq-provider
  #配置rabbitmq服务器
  rabbitmq:
    host: 127.0.0.1
    port: 5672
    username: guest
    password: guest
    virtual-host: /


直连交换机

DirectRabbitConfig

package com.example.rabbitmqprovider.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.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author 吴伟伟
 * @description DirectRabbitConfig
 * @date 2023/6/27 16:10
 */

@Configuration
public class DirectRabbitConfig {

    //队列起名:TestDirectQueue
    @Bean
    public Queue TestDirectQueue(){
        /*
            durable:是否持久化,默认false。持久化队列:会被存储在磁盘上,当消息代理重启时仍然存在。   暂存队列:当前连接有效
            exclusive:默认false,只能被当前创建的连接使用,当连接关闭后队列即被删除;
            autoDelete:默认false, 是否自动删除,当没有生产者或者消费者使用此队列,该队列会自动删除
         */
        //new Queue("TestDirectQueue",true,true,true);

        return new Queue("TestDirectQueue",true);
    }



    //Direct交换机  起名:TestDirectExchange
    @Bean
    public DirectExchange TestDirectExchange(){
        return new DirectExchange("TestDirectExchange",true,false);

    }


    //绑定   将队列和交换机绑定,并设置用于匹配键  : TestDirectRouting
    @Bean
    public Binding bindingDirect(){
        //BindingBuilder.bind(队列).to(交换机).with(路由键routingKey);
        return BindingBuilder.bind(TestDirectQueue()).to(TestDirectExchange()).with("TestDirectRouting");
    }

    @Bean
    public DirectExchange lonelyDirectExchange(){
        return new DirectExchange("lonelyDirectExchange");
    }



}

SendMessageController

package com.example.rabbitmqprovider.controller;

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.UUID;

/**
 * @author 吴伟伟
 * @description SendMessageController
 * @date 2023/6/27 16:27
 */

@RestController
@RequestMapping("/mq")
public class SendMessageController {

    @Autowired
    private RabbitTemplate rabbitTemplate; //使用RabbitTemplate,提供了接收,发送等方法


    @RequestMapping("/sendDirectMessage")
    public  String sendDirectMessage(){
        String messageId = String.valueOf(UUID.randomUUID());
        String messageData="test message , hello";
        String createTime= LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        HashMap<String, Object> map = new HashMap<>();
        map.put("messageId",messageId);
        map.put("messageData",messageData);
        map.put("createTime",createTime);

        //将消息携带绑定键值:TestDirectRouting 发送到交换机TestDirectExchange
        rabbitTemplate.convertAndSend("TestDirectExchange","TestDirectRouting",map);//  交换机  路由  消息
        return "ok";
    }




}

 主类启动

 使用postman调一下接口

看一下rabbitmq管理界面,有一条未被消费的消息

接下来消费者微服务

 pom.xml同上

application.yml

server:
  port: 8022

spring:
  application:
    #项目名称
    name: rabbitmq-consumer
  #配置rabbitmq服务器
  rabbitmq:
    host: 127.0.0.1
    port: 5672
    username: guest
    password: guest
    virtual-host: /



监听消息队列

package com.example.rabbitmqconsumer.receiver;

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

import java.util.Map;

/**
 * @author 吴伟伟
 * @description DirectReciver
 * @date 2023/6/27 17:29
 */

@Component
@RabbitListener(queues = "TestDirectQueue") //监听队列TestDirectQueue
public class DirectReciver {

    @RabbitHandler
    public void process(Map testMessage){
        System.out.println("DirectReciver消费者收到消息:"+testMessage.toString());

    }
}

启动服务后,发现消息被消费了

如果多个消费者监听同一个队列会发现

会发现,是轮询方式进行消息消费

主题交换机----Topic Exchange

生产者

TopicRabbitConfig

package com.example.rabbitmqprovider.config;

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

/**
 * @author 吴伟伟
 * @description TopicRabbitConfig
 * @date 2023/6/28 14:24
 */

@Configuration
public class TopicRabbitConfig {

    public final static String MAN="topic.man";
    public final static String WOMAN="topic.woman";

    //创建队列
    @Bean
    public Queue firstQueue(){
        return new Queue(MAN);
    }

    @Bean
    public Queue SecondQueue(){
        return new Queue(WOMAN);
    }

    //创建主题交换机
    @Bean
    public TopicExchange exchange(){
        return new TopicExchange("TopicExchange");
    }

    //将firstQueue和topicExchange绑定,而且绑定的键值为topic.man
    //这样只要是消息携带的路由键是topic.man,才会分发到该队列
    @Bean
    public Binding bindingExchangeMessage(){
        return BindingBuilder.bind(firstQueue()).to(exchange()).with(MAN);
    }
    //将SecondQueue和topicExchange绑定,而且绑定的键值为topic.#
    //这样只要是消息携带的路由键是topic.开头,都会分发到该队列
    @Bean
    public Binding bindingExchangeMessage2(){
        return BindingBuilder.bind(SecondQueue()).to(exchange()).with("topic.#");
    }








}

 

    @RequestMapping("/sendTopicMessage1")
    public  String sendTopicMessage1(){
        String messageId = String.valueOf(UUID.randomUUID());
        String messageData=" message:man";
        String createTime= LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        HashMap<String, Object> map = new HashMap<>();
        map.put("messageId",messageId);
        map.put("messageData",messageData);
        map.put("createTime",createTime);

        rabbitTemplate.convertAndSend("TopicExchange","topic.man",map);//  交换机  路由  消息
        return "ok";
    }


    @RequestMapping("/sendTopicMessage2")
    public  String sendTopicMessage2(){
        String messageId = String.valueOf(UUID.randomUUID());
        String messageData="message:woman";
        String createTime= LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        HashMap<String, Object> map = new HashMap<>();
        map.put("messageId",messageId);
        map.put("messageData",messageData);
        map.put("createTime",createTime);

        rabbitTemplate.convertAndSend("TopicExchange","topic.woman",map);//  交换机  路由  消息
        return "ok";
    }

消费者

TopicManReciver

package com.example.rabbitmqconsumer.receiver;

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

import java.util.Map;

@Component
@RabbitListener(queues = "topic.man") //监听队列
public class TopicManReciver {

    @RabbitHandler
    public void process(Map testMessage){
        System.out.println("TopicManReciver消费者收到消息:"+testMessage.toString());

    }
}

TopicWomanReciver

package com.example.rabbitmqconsumer.receiver;

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

import java.util.Map;

@Component
@RabbitListener(queues = "topic.woman") //监听队列
public class TopicWomanReciver {

    @RabbitHandler
    public void process(Map testMessage){
        System.out.println("TopicWomanReciver消费者收到消息:"+testMessage.toString());

    }
}

启动生产者和消费者,使用postman发请求

http://127.0.0.1:8021/mq/sendTopicMessage1

http://127.0.0.1:8021/mq/sendTopicMessage2

http://127.0.0.1:8021/mq/sendDirectMessage

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Spring Boot框架可以很容易地与RabbitMQ进行集成。为了实现这个目标,你需要在项目的依赖项中添加两个关键的依赖项。首先,你需要添加spring-boot-starter-amqp依赖项,它提供了与RabbitMQ进行通信的必要类和方法。其次,你还需要添加spring-boot-starter-web依赖项,以便在项目中使用Web功能。 在你的项目中创建两个Spring Boot应用程序,一个是RabbitMQ的生产者,另一个是消费者。通过这两个应用程序,你可以实现消息的发送和接收。生产者应用程序负责将消息发送到RabbitMQ的消息队列,而消费者应用程序则负责从队列中接收并处理消息。这样,你就可以实现基于RabbitMQ的消息传递系统。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [SpringBoot整合RabbitMQ](https://blog.csdn.net/K_kzj_K/article/details/106642250)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] - *2* [Springboot 整合RabbitMq ,用心看完这一篇就够了](https://blog.csdn.net/qq_35387940/article/details/100514134)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] - *3* [undefined](undefined)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Java-请多指教

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值