SpringBoot整合RabbitMQ

序言

如果不知道如何使用Idea创建SpringBoot项目或者不知道如何在Windows系统中搭建RabbitMQ环境,可以参考如下博客

https://blog.csdn.net/w8827130/article/details/109934393    最简单SpringBoot项目创建

https://blog.csdn.net/w8827130/article/details/109946723    Windows安装RabbitMQ

SpringBoot项目结构

RabbitMQ

pom文件

<?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.4.0</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>springboot</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-amqp</artifactId>
        </dependency>
    </dependencies>

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

</project>

SpringBoot的pom.xml里新增了spring-boot-starter-amqp依赖用于引入RabbitMQ

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

application.yml

配置文件中设置项目访问端口为8081,还有rabbitmq的配置

server:
  port: 8081
spring:
  application:
    name: rabbitmq-demo
  rabbitmq:
    host: 127.0.0.1
    port: 5672
    username: guest
    password: guest

RabbitConfig.java

配置RabbitMQ,声明queue、exchange、bingding

queue:hello、topic.message、topic.messages、fanout.A、fanout.B、fanout.C

exchange:topicExchange、fanoutExchange、

bingding:topic.message与topicExchange绑定(routingKey=topic.message),topic.messages与topicExchange绑定(routingKey=topic.#),fanout.A、fanout.B、fanout.C与fanoutExchange绑定

package com.example.springboot.config;

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

@Configuration
public class RabbitConfig {

    @Bean
    public Queue helloQueue() {
        return new Queue("hello");
    }

    @Bean
    public Queue userQueue() {
        return new Queue("user");
    }
    
    @Bean
    public Queue queueMessage() {
        return new Queue("topic.message");
    }

    @Bean
    public Queue queueMessages() {
        return new Queue("topic.messages");
    }

    @Bean
    public Queue AMessage() {
        return new Queue("fanout.A");
    }

    @Bean
    public Queue BMessage() {
        return new Queue("fanout.B");
    }

    @Bean
    public Queue CMessage() {
        return new Queue("fanout.C");
    }

    /**
     * 创建TopicExchange
     * @return TopicExchange
     */
    @Bean
    TopicExchange topicExchange() {
        return new TopicExchange("topicExchange");
    }

    /**
     * 创建FanoutExchange
     * @return FanoutExchange
     */
    @Bean
    FanoutExchange fanoutExchange() {
        return new FanoutExchange("fanoutExchange");
    }

    /**
     * 将queueMessage队列与TopicExchange交换机绑定,使用routingKey=topic.message
     * @param queueMessage
     * @param topicExchange
     * @return Binding
     */
    @Bean
    Binding bindingExchangeMessage(Queue queueMessage, TopicExchange topicExchange) {
        return BindingBuilder.bind(queueMessage).to(topicExchange).with("topic.message");
    }

    /**
     * 将queueMessage队列与TopicExchange交换机绑定,使用routingKey=topic.#(# 匹配一个或者多个词;* 仅能匹配一个词)
     * @param queueMessages
     * @param topicExchange
     * @return Binding
     */
    @Bean
    Binding bindingExchangeMessages(Queue queueMessages, TopicExchange topicExchange) {
        return BindingBuilder.bind(queueMessages).to(topicExchange).with("topic.#");
    }

    /**
     * AMessage与fanoutExchange绑定
     * @param AMessage
     * @param fanoutExchange
     * @return Binding
     */
    @Bean
    Binding bindingExchangeA(Queue AMessage,FanoutExchange fanoutExchange) {
        return BindingBuilder.bind(AMessage).to(fanoutExchange);
    }

    /**
     * bMessage与fanoutExchange绑定
     * @param BMessage
     * @param fanoutExchange
     * @return Binding
     */
    @Bean
    Binding bindingExchangeB(Queue BMessage, FanoutExchange fanoutExchange) {
        return BindingBuilder.bind(BMessage).to(fanoutExchange);
    }

    /**
     * CMessage与fanoutExchange绑定
     * @param CMessage
     * @param fanoutExchange
     * @return Binding
     */
    @Bean
    Binding bindingExchangeC(Queue CMessage, FanoutExchange fanoutExchange) {
        return BindingBuilder.bind(CMessage).to(fanoutExchange);
    }
}

发送方式

Direct

将消息直接发送给特定的queue(这种方式几乎不会被用,违背了RabbitMQ解耦的初衷)

Sender.java

package com.example.springboot.sender;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.Date;

@Component
public class Sender {

    private static final Logger log = LoggerFactory.getLogger(Sender.class);

    @Autowired
    public AmqpTemplate amqpTemplate;

    public void send(){
        String context = "hello"+ new Date();
        log.info("Sender:" + context);
        this.amqpTemplate.convertAndSend( "hello",context);
    }
}

Receiver.java

package com.example.springboot.receiver;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Component
public class Receiver {

    private static final Logger log = LoggerFactory.getLogger(Receiver.class);

    //监听器监听指定的Queue
    @RabbitListener(queues = "hello")
    public void process(String hello) {
        log.info("ReceiverHello:" + hello);
    }


}

实体类的传输

User.java

package com.example.springboot.pojo;

import java.io.Serializable;

public class User implements Serializable {

    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

UserSender.java

package com.example.springboot.sender;

import com.example.springboot.pojo.User;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class UserSender {

    @Autowired
    private AmqpTemplate amqpTemplate;

    public void send(){
        User user = new User();
        user.setName("daimouren");
        amqpTemplate.convertAndSend("user",user);
    }
}

UserReceiver.java

package com.example.springboot.receiver;

import com.example.springboot.pojo.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;

@Component
@RabbitListener(queues = "user")
public class UserReceiver {

    private static final Logger log = LoggerFactory.getLogger(Receiver.class);

    @RabbitHandler
    public void process(User user){
        log.info("listener user:{}",user.getName());
    }
}

Topic

TopicSender.java

package com.example.springboot.sender;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class TopicSender {

    private static final Logger log = LoggerFactory.getLogger(TopicSender.class);

    @Autowired
    public AmqpTemplate amqpTemplate;

    public void sendTopic(){
        amqpTemplate.convertAndSend("topicExchange","topic.message","Topic-message1");

        amqpTemplate.convertAndSend("topicExchange","topic.messages","Topic-message2");

        amqpTemplate.convertAndSend("topicExchange","topic.test3.tes2","Topic-message3");
    }

}

TopicReceiver.java

package com.example.springboot.receiver;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Component
public class TopicReceiver {

    private static final Logger log = LoggerFactory.getLogger(TopicReceiver.class);

    @RabbitListener(queues = "topic.message")
    public void process1(String msg){
        log.info("TopicReceiver1:"+msg);
    }
    
    @RabbitListener(queues = "topic.messages")
    public void process2(String msg){
        log.info("TopicReceiver2:"+msg);
    }
}

Fanout

FanoutSender.java

package com.example.springboot.sender;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class FanoutSender {

    private static final Logger log = LoggerFactory.getLogger(FanoutSender.class);

    @Autowired
    public AmqpTemplate amqpTemplate;

    public void sendFanout(){
        String context = "fanoutExchange:"+ new Date();
        log.info("Sender:" + context);
        this.amqpTemplate.convertAndSend("fanoutExchange","abcd.ee",context);
    }
}

FanoutReceiver.java

package com.example.springboot.receiver;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Component
public class FanoutReceiver {

    private static final Logger log = LoggerFactory.getLogger(FanoutReceiver.class);

    //监听器监听指定的Queue
    @RabbitListener(queues = "fanout.A")
    public void processfanoutA(String message) {
        log.info("ReceiverfanoutA:" + message);
    }

    //监听器监听指定的Queue
    @RabbitListener(queues = "fanout.B")
    public void processfanoutB(String message) {
        log.info("ReceiverfanoutB:" + message);
    }

    //监听器监听指定的Queue
    @RabbitListener(queues = "fanout.C")
    public void processfanoutC1(String message) {
        log.info("ReceiverfanoutC1:" + message);
    }
}

RabbitmqController.java

创建Controller接口,对各种场景的mq发送的测试

package com.example.springboot.controller;

import com.example.springboot.sender.FanoutSender;
import com.example.springboot.sender.Sender;
import com.example.springboot.sender.TopicSender;
import com.example.springboot.sender.UserSender;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class RabbitmqController {

    @Autowired
    private Sender sender;

    @Autowired
    private UserSender userSender;

    @Autowired
    private TopicSender topicSender;

    @Autowired
    private FanoutSender fanoutSender;

    @RequestMapping("sendhello")
    public String sendhello() {
        sender.send();
        return "send success!";
    }

    @RequestMapping("sendfanout")
    public String sendfanout() {
        fanoutSender.sendFanout();
        return "send success!";
    }

    @RequestMapping("senduser")
    public String senduser() {
        userSender.send();
        return "send success!";
    }

    @RequestMapping("sendtopic")
    public String sendtopic() {
        topicSender.sendTopic();
        return "send success!";
    }
}

 

参考文章

https://blog.csdn.net/typ1805/article/details/82835318

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值