栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

【RabbitMQ】04--RabbitMQ + SpringBoot

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【RabbitMQ】04--RabbitMQ + SpringBoot

一,准备工作 2.创建SpringBoot项目

2.添加RabbitMQ依赖

3.修改pom.xml文件


    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.3.2.RELEASE
         
    
    com.drhj
    rabbitmq-springboot
    0.0.1-SNAPSHOT
    rabbitmq-springboot
    Demo project for Spring Boot
    
        1.8
    
    
        
            org.springframework.boot
            spring-boot-starter-amqp
        

        
            org.springframework.boot
            spring-boot-starter-test
            test
        
        
            org.springframework.amqp
            spring-rabbit-test
            test
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    


4.配置application.yml
spring:
  rabbitmq:
    host: 192.168.64.140   #服务ip
    port: 5672
    username: admin
    password: admin
    virtual-host: drhj #虚拟空间
5.RabbitMQ六种工作模式

六种工作模式

二.简单模式 1.主程序

因为我们测试六种模式,所以如果使用系统提供的启动类,根据spring启动类的特性,启动其所在文件夹下的所有类,显然浪费资源,所以我们在每种模式的测试文件中都写一个启动类。
Spring提供的Queue类,是队列的封装对象,它封装了队列的参数信息.
RabbitMQ的自动配置类,会发现这些Queue实例,并在RabbitMQ服务器中定义这些队列.

package com.drhj.rabbitmqspringboot.m1;

import org.springframework.amqp.core.Queue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

import javax.annotation.PostConstruct;


@SpringBootApplication
public class Main {
    public static void main(String[] args) {
        SpringApplication.run(Main.class,args);
    }
    
    @Bean
    public Queue helloworld() {
        //return new Queue("helloworld"); //默认true,false,false
        return new Queue("helloworld",true);
    }
    @Autowired
    private Producer p;
    
    @PostConstruct
    public void test() {
        p.send();
    }
}
2.生产者

AmqpTemplate是rabbitmq客户端API的一个封装工具,提供了简便的方法来执行消息操作.
AmqpTemplate由自动配置类自动创建

package com.drhj.rabbitmqspringboot.m1;

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

@Component
public class Producer {
    @Autowired
    private AmqpTemplate t;
    
    public void send() {
        //自动转换byte[]数组
        t.convertAndSend("helloworld","Hello world!");
    }
}
3.消费者

通过@RabbitListener从指定的队列接收消息
使用@RebbitHandler注解的方法来处理消息

package com.drhj.rabbitmqspringboot.m1;

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

@Component
@RabbitListener(queues = "helloworld")
public class Consumer {
    @RabbitHandler
    public void receive(String s) {
        System.out.println("收到数据:" + s);
    }
}

或者也可以写成如下形式

@Component
public class SimpleReceiver {
	@RabbitListener(queues = "helloworld")
	public void receive(String s) {
		System.out.println("收到: "+s);
	}
}

与上者不同的是,上者如果想要多个消费者,需要创建多个类;而下者只需要添加几个方法即可
另外,@RabbitListener 注解中也可以直接定义队列:

@RabbitListener(queuesToDeclare = @Queue(name = "helloworld",durable = "false"))
4.测试

上述Main方法中的

 @Autowired
    private Producer p;
    
    @PostConstruct
    public void test() {
        p.send();
    }

就是用于测试
启动主程序,可能需要启动两次,查看结果

三,工作模式 1.主程序

在主程序中创建名为task_queue的持久队列

package com.drhj.rabbitmqspringboot.m2;

import org.springframework.amqp.core.Queue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

import javax.annotation.PostConstruct;


@SpringBootApplication
public class Main {
    public static void main(String[] args) {
        SpringApplication.run(Main.class,args);
    }
    
    @Bean
    public Queue helloworld() {
        //return new Queue("helloworld"); //默认true,false,false
        return new Queue("task_queue",true);
    }
    @Autowired
    private Producer p;
    
    @PostConstruct
    public void test() {
        //在新的线程中执行死循环,不阻塞spring 主线程执行
        new Thread(() -> p.send()).start();
    }
}
2.生产者
package com.drhj.rabbitmqspringboot.m2;

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

import java.util.Scanner;

@Component
public class Producer {
    @Autowired
    private AmqpTemplate t;
    
    public void send() {
        while (true) {
            System.out.println("输入消息: ");
            String s = new Scanner(System.in).nextLine();
            //自动转换byte[]数组
            t.convertAndSend("task_queue",s);
        }
    }
}
3.消费者

创建多个消费者

package com.drhj.rabbitmqspringboot.m2;

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

@Component
public class Consumer {
    
    @RabbitListener(queues = "task_queue")
    public void receive1(String s) {
        System.out.println("消费者1收到数据:" + s);
    }
    @RabbitListener(queues = "task_queue")
    public void receive2(String s) {
        System.out.println("消费者2收到数据:" + s);
    }
}
4.测试

上述Main方法中的

@Autowired
    private Producer p;
    
    @PostConstruct
    public void test() {
        //在新的线程中执行死循环,不阻塞spring 主线程执行
        new Thread(() -> p.send()).start();
    }

这里创建一个线程的原因是如果@PostConstruct下的程序一直执行死循环,则后续程序无法正常执行了。

5.消息的合理分发和持久化
 

如果要改成非持久化

//如果需要设置消息为非持久化,可以取得消息的属性对象,修改它的deliveryMode属性
	t.convertAndSend("task_queue", (Object) s, new MessagePostProcessor() {
		@Override
		public Message postProcessMessage(Message message) throws AmqpException {
			MessageProperties props = message.getMessageProperties();
			props.setDeliveryMode(MessageDeliveryMode.NON_PERSISTENT);
			return message;
		}
	});
四,发布和订阅模式 1.主程序

创建 FanoutExcnahge 实例, 封装 fanout 类型交换机定义信息.
spring boot 的自动配置类会自动发现交换机实例, 并在 RabbitMQ 服务器中定义该交换机.

package com.drhj.rabbitmqspringboot.m3;

import org.springframework.amqp.core.FanoutExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

import javax.annotation.PostConstruct;

@SpringBootApplication
public class Main {
    public static void main(String[] args) {
        SpringApplication.run(Main.class,args);
    }
    @Bean
    public FanoutExchange logs() {
        return new FanoutExchange("logs",false,false);
    }
    @Autowired
    private Producer p;
    
    @PostConstruct
    public void test() {
        //在新的线程中执行死循环,不阻塞spring 主线程执行
        new Thread(() -> p.send()).start();
    }
}
2.生产者

生产者向指定的交换机 logs 发送数据.
不需要指定队列名或路由键, 即使指定也无效, 因为 fanout 交换机会向所有绑定的队列发送数据, 而不是有选择的发送.

package com.drhj.rabbitmqspringboot.m3;

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

import java.util.Scanner;

@Component
public class Producer {
    @Autowired
    private AmqpTemplate t;
    
    public void send() {
        while (true) {
            System.out.println("输入消息: ");
            String s = new Scanner(System.in).nextLine();
            //自动转换byte[]数组
            //t.convertAndSend("logs","队列名或路由键",s);
            t.convertAndSend("logs","",s);
        }
    }
}
3.消费者

消费者需要执行以下操作:

  • 定义随机队列(随机命名,非持久,排他,自动删除)
  • 定义交换机(可以省略, 已在主程序中定义)
  • 将队列绑定到交换机
    spring boot 通过注解完成以上操作:
@RabbitListener(bindings = @QueueBinding(
            value = @Queue(),     //自动设置的参数:随机命名,false,true,true 非持久,独占,自动删除
            exchange = @Exchange(name = "logs",declare = "false") //declare = "false" 不创建交换机,只是引用存在的交换机
    ))
package com.drhj.rabbitmqspringboot.m3;

import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Component
public class Consumer {
    
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(),     //自动设置的参数:随机命名,false,true,true 非持久,独占,自动删除
            exchange = @Exchange(name = "logs",declare = "false") //declare = "false" 不创建交换机,只是引用存在的交换机
    ))
    public void receive1(String s) {
        System.out.println("消费者1收到数据:" + s);
    }
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(),     //自动设置的参数:随机命名,false,true,true 非持久,独占,自动删除
            exchange = @Exchange(name = "logs",declare = "false") //declare = "false" 不创建交换机,只是引用存在的交换机
    ))
    public void receive2(String s) {
        System.out.println("消费者2收到数据:" + s);
    }
}
4.测试

五,路由模式

与发布和订阅模式代码类似, 只是做以下三点调整:

  • 使用 direct 交换机
  • 队列和交换机绑定时, 设置绑定键
  • 发送消息时, 指定路由键
1. 主程序

主程序中使用 DirectExcnahge 对象封装交换机信息, spring boot 自动配置类会自动发现这个对象, 并在 RabbitMQ 服务器上定义这个交换机.

package com.drhj.rabbitmqspringboot.m4;

import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.FanoutExchange;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

import javax.annotation.PostConstruct;

@SpringBootApplication
public class Main {
    public static void main(String[] args) {
        SpringApplication.run(Main.class,args);
    }
    @Bean
    public DirectExchange logs() {
        return new DirectExchange("direct_logs",false,false);
    }
    @Autowired
    private Producer p;
    
    @PostConstruct
    public void test() {
        //在新的线程中执行死循环,不阻塞spring 主线程执行
        new Thread(() -> p.send()).start();
    }
}
2.生产者

生产者向指定的交换机发送消息, 并指定路由键.

package com.drhj.rabbitmqspringboot.m4;

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

import java.util.Scanner;

@Component
public class Producer {
    @Autowired
    private AmqpTemplate t;
    
    public void send() {
        while (true) {
            System.out.println("输入消息: ");
            String s = new Scanner(System.in).nextLine();
            System.out.println("输入关键词: ");
            String k = new Scanner(System.in).nextLine();
            //自动转换byte[]数组
            //t.convertAndSend("logs","队列名或路由键",s);
            t.convertAndSend("direct_logs",k,s);
        }
    }
}
3.消费者

消费者通过注解来定义随机队列, 绑定到交换机, 并指定绑定键:

@RabbitListener(bindings = @QueueBinding(
            value = @Queue(),     //自动设置的参数:随机命名,false,true,true 非持久,独占,自动删除
            exchange = @Exchange(name = "direct_logs",declare = "false"), //declare = "false" 不创建交换机,只是引用存在的交换机
            key = {"error"}
    ))
package com.drhj.rabbitmqspringboot.m4;

import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Component
public class Consumer {
    
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(),     //自动设置的参数:随机命名,false,true,true 非持久,独占,自动删除
            exchange = @Exchange(name = "direct_logs",declare = "false"), //declare = "false" 不创建交换机,只是引用存在的交换机
            key = {"error"}
    ))
    public void receive1(String s) {
        System.out.println("消费者1收到数据:" + s);
    }
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(),     //自动设置的参数:随机命名,false,true,true 非持久,独占,自动删除
            exchange = @Exchange(name = "direct_logs",declare = "false"), //declare = "false" 不创建交换机,只是引用存在的交换机
            key = {"info","error","warning"}
    ))
    public void receive2(String s) {
        System.out.println("消费者2收到数据:" + s);
    }
}

4.测试

六,主题模式

主题模式不过是具有特殊规则的路由模式, 代码与路由模式基本相同, 只做如下调整:

  • 使用 topic 交换机
  • 使用特殊的绑定键和路由键规则
1.主程序
package com.drhj.rabbitmqspringboot.m5;

import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

import javax.annotation.PostConstruct;

@SpringBootApplication
public class Main {
    public static void main(String[] args) {
        SpringApplication.run(Main.class,args);
    }
    @Bean
    public TopicExchange logs() {
        return new TopicExchange("topic_logs",false,false);
    }
    @Autowired
    private Producer p;
    
    @PostConstruct
    public void test() {
        //在新的线程中执行死循环,不阻塞spring 主线程执行
        new Thread(() -> p.send()).start();
    }
}
2.生产者
package com.drhj.rabbitmqspringboot.m5;

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

import java.util.Scanner;

@Component
public class Producer {
    @Autowired
    private AmqpTemplate t;
    
    public void send() {
        while (true) {
            System.out.println("输入消息: ");
            String s = new Scanner(System.in).nextLine();
            System.out.println("输入关键词: ");
            String k = new Scanner(System.in).nextLine();
            //自动转换byte[]数组
            //t.convertAndSend("logs","队列名或路由键",s);
            t.convertAndSend("topic_logs",k,s);
        }
    }
}
3.消费者
package com.drhj.rabbitmqspringboot.m5;

import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Component
public class Consumer {
    
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(),     //自动设置的参数:随机命名,false,true,true 非持久,独占,自动删除
            exchange = @Exchange(name = "topic_logs",declare = "false"), //declare = "false" 不创建交换机,只是引用存在的交换机
            key = {"*.orange.*"}
    ))
    public void receive1(String s) {
        System.out.println("消费者1收到数据:" + s);
    }
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(),     //自动设置的参数:随机命名,false,true,true 非持久,独占,自动删除
            exchange = @Exchange(name = "topic_logs",declare = "false"), //declare = "false" 不创建交换机,只是引用存在的交换机
            key = {"*.*.rabbit","lazy.#"}
    ))
    public void receive2(String s) {
        System.out.println("消费者2收到数据:" + s);
    }
}
4.测试

七,RPC异步调用 1.主程序

主程序中定义两个队列

  • 发送调用信息的队列: rpc_queue
  • 返回结果的队列: 随机命名
package com.drhj.rabbitmqspringboot.m6;

import java.util.Scanner;
import java.util.UUID;

import org.springframework.amqp.core.Queue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

import javax.annotation.PostConstruct;

@SpringBootApplication
public class Main {

    public static void main(String[] args) {
        SpringApplication.run(Main.class, args);
    }
    @Bean
    public Queue sendQueue() {
        return new Queue("rpc_queue",false);
    }
    //给队列添加名称
    @Bean
    public Queue rndQueue() {
        return new Queue(UUID.randomUUID().toString(), false);
    }
    @Autowired
    RpcClient client;
    
    @PostConstruct
    public void test() {
        //在新的线程中执行死循环,不阻塞spring 主线程执行
        new Thread(() -> {
            while (true) {
                System.out.println("求第几个斐波那契数: ");
                int n = new Scanner(System.in).nextInt();
                client.send(n);
            }
        }).start();
    }
}

2.服务端

从rpc_queue接收调用数据, 执行运算求斐波那契数,并返回计算结果.
@Rabbitlistener注解对于具有返回值的方法:

  • 会自动获取 replyTo 属性
  • 自动获取 correlationId 属性
  • 向 replyTo 属性指定的队列发送计算结果, 并携带 correlationId 属性
package com.drhj.rabbitmqspringboot.m6;

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

@Component
public class RpcServer {
    @RabbitListener(queues = "rpc_queue")
    public long getFbnq(int n) {
        return f(n);
    }

    private long f(int n) {
        if (n==1 || n==2) {
            return 1;
        }
        return f(n-1) + f(n-2);
    }
}
3.客户端

使用 SPEL 表达式获取随机队列名: “#{rndQueue.name}”
发送调用数据时, 携带随机队列名和correlationId
从随机队列接收调用结果, 并获取correlationId

package com.drhj.rabbitmqspringboot.m6;

import java.util.UUID;

import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

@Component
public class RpcClient {
    @Autowired
    AmqpTemplate t;

    @Value("#{rndQueue.name}")
    String rndQueue;

    public void send(int n) {
        // 发送调用信息时, 通过前置消息处理器, 对消息属性进行设置, 添加返回队列名和关联id
        t.convertAndSend("rpc_queue", (Object)n, new MessagePostProcessor() {
            @Override
            public Message postProcessMessage(Message message) throws AmqpException {
                MessageProperties p = message.getMessageProperties();
                p.setReplyTo(rndQueue);
                p.setCorrelationId(UUID.randomUUID().toString());
                return message;
            }
        });
    }

    //从随机队列接收计算结果
    @RabbitListener(queues = "#{rndQueue.name}")
    public void receive(long r, @Header(name=AmqpHeaders.CORRELATION_ID) String correlationId) {
        System.out.println("nn"+correlationId+" - 收到: "+r);
    }
}
4.测试

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/351188.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号