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.2.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>cn.tedu</groupId>
<artifactId>rabbitmq-springboot</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>rabbitmq-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-amqp</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.amqp</groupId>
<artifactId>spring-rabbit-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
在application.yml里面配置连接rabbitmq服务器
spring:
rabbitmq:
#virtual-host: /pd
host: 192.168.64.140
username: admin
password: admin
简单模式
Spring提供的Queue类,是队列的封装对象,它封装了队列的参数信息.
RabbitMQ的自动配置类,会发现这些Queue实例,并在RabbitMQ服务器中定义这些队列.
主程序
package cn.tedu.m1;
import org.springframework.amqp.core.Queue;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class Main {
public static void main(String[] args) {
SpringApplication.run(Main.class, args);
}
@Bean
public Queue helloworldQueue() {
return new Queue("hello",false);
}
}
生产者
package cn.tedu.m1;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class Sender {
@Autowired
AmqpTemplate t;
public void send() {
t.convertAndSend("hello", "hello world"+System.currentTimeMillis());
}
}
消费者
package cn.tedu.m1;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
@Component
@RabbitListener(queues = "hello")
public class Receive {
@RabbitHandler
public void receive(String msg) {
System.out.println("收到的消息:"+msg);
}
}
测试类
package cn.tedu.m1;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
public class SimpleTest {
@Autowired
Sender sender;
@Test
public void text1() throws Exception{
sender.send();
}
}
工作模式
主程序
package cn.tedu.m2;
import org.springframework.amqp.core.Queue;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class Main {
public static void main(String[] args) {
SpringApplication.run(Main.class, args);
}
@Bean
public Queue task_queue() {
//持久,非拍他,非自动删除
return new Queue("task_queue");
}
}
生产者
package cn.tedu.m2;
import java.util.Scanner;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class Sender {
@Autowired
AmqpTemplate t;
public void send() {
while (true) {
System.out.println("输入:");
String s = new Scanner(System.in).nextLine();
//spring默认将消息的DeliveryMode 设置为 PERSISTENT 持久化,
t.convertAndSend("task_queue",s);
}
}
}
消费者
package cn.tedu.m2;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
@Component
public class Receive {
@RabbitListener(queues = "task_queue")
public void receive1(String s) throws InterruptedException {
System.out.println("receive1-收到:"+s);
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '.') {
Thread.sleep(1000);
}
}
}
@RabbitListener(queues = "task_queue")
public void receive2(String s) throws InterruptedException {
System.out.println("receive2-收到:"+s);
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '.') {
Thread.sleep(1000);
}
}
}
}
测试类
package cn.tedu.m2;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
public class WorkTest {
@Autowired
Sender sender;
@Test
void test1() throws Exception {
sender.send();
}
}
设置ack
在 spring boot 中提供了三种确认模式:
- NONE - 使用rabbitmq的自动确认
- AUTO - 使用rabbitmq的手动确认, springboot会自动发送确认回执
(默认) - MANUAL - 使用rabbitmq的手动确认, 且必须手动执行确认操作
默认的 AUTO 模式中, 处理消息的方法抛出异常, 则表示消息没有被正确处理, 该消息会被重新发送.
抓取数量
将 qos 设置成 1, 每次只接收一条消息, 处理完成后才接收下一条消息.
spring:
rabbitmq:
#virtual-host: /pd
host: 192.168.64.140
username: admin
password: admin
listener:
simple:
prefetch: 1 # qos=1, 默认250每次只接收一条消息, 处理完成后才接收下一条消息
# acknowledgeMode: NONE # rabbitmq的自动确认
acknowledgeMode: AUTO # rabbitmq的手动确认, springboot会自动发送确认回执 (默认)
# acknowledgeMode: MANUAL # rabbitmq的手动确认, springboot不发送回执, 必须自己编码发送回执
发布和订阅模式
FanoutExcnahge 交换机
主程序
package cn.tedu.m3;
import org.springframework.amqp.core.FanoutExchange;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class Main {
public static void main(String[] args) {
SpringApplication.run(Main.class, args);
}
/**
* 创建fanoutExchange实例封装交换机名
* 自动配置类会自动发现这个实例,并连接rabbitmq来定义这个交换机
* @return
*/
@Bean
public FanoutExchange logsExchange() {
return new FanoutExchange("logsss");
}
}
生产者
package cn.tedu.m3;
import java.util.Scanner;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class Sender {
@Autowired
AmqpTemplate t;
public void send() {
while (true) {
System.out.println("输入:");
String s = new Scanner(System.in).nextLine();
t.convertAndSend("logsss", "", s);
}
}
}
消费者
package cn.tedu.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 Receive {
/**
* 定义随机队列(随机命名,非持久,排他,自动删除)
* 可定义 交换机(已在主程序定义,课省略)
* 绑定(将队列绑定至交换机)
* @param s
* @throws Exception
*/
//@QueueBinding进行绑定设置 value = @Queue,定义随机队列 exchange = @Exchange指定logs交换机
@RabbitListener(bindings = @QueueBinding(value = @Queue,exchange = @Exchange(name = "logsss",declare = "false")))
public void receive1(String s) throws Exception {
System.out.println("receiver1 - 收到: "+s);
}
@RabbitListener(bindings = @QueueBinding(value = @Queue,exchange = @Exchange(name = "logsss",declare = "false")))
public void receive2(String s) throws Exception {
System.out.println("receiver2 - 收到: "+s);
}
}
测试类
package cn.tedu.m3;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
public class PublishSubscribeTests {
@Autowired
Sender sender;
@Test
void test1() throws Exception {
sender.send();
}
}
路由模式
DirectExcnahge 交换机
主程序
package cn.tedu.m4;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.FanoutExchange;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class Main {
public static void main(String[] args) {
SpringApplication.run(Main.class, args);
}
//路由模式
@Bean
public DirectExchange directExchange() {
return new DirectExchange("directt_logs");
}
}
生产者
package cn.tedu.m4;
import java.util.Scanner;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class Sender {
@Autowired
AmqpTemplate t;
public void send() {
while (true) {
System.out.println("输入:");
String s = new Scanner(System.in).nextLine();
System.out.println("输入key:");
String key = new Scanner(System.in).nextLine();
t.convertAndSend("directt_logs", key, s);
}
}
}
消费者
package cn.tedu.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 Receive {
/**
* 定义随机队列(随机命名,非持久,排他,自动删除)
* 可定义 交换机(已在主程序定义,课省略)
* 绑定(将队列绑定至交换机)
* @param s
* @throws Exception
*/
//@QueueBinding进行绑定设置 value = @Queue,定义随机队列 exchange = @Exchange指定logs交换机
@RabbitListener(bindings = @QueueBinding(
value = @Queue,
exchange = @Exchange(name = "directt_logs",declare = "false"),
key = {"error"}))
public void receive1(String s) throws Exception {
System.out.println("receiver1 - 收到: "+s);
}
@RabbitListener(bindings = @QueueBinding(
value = @Queue,
exchange = @Exchange(name = "directt_logs",declare = "false"),
key = {"error","info"}))
public void receive2(String s) throws Exception {
System.out.println("receiver2 - 收到: "+s);
}
}
测试类
package cn.tedu.m4;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
public class RouteTests {
@Autowired
Sender sender;
@Test
void test1() throws Exception {
sender.send();
}
}
主题模式
topic交换机
主程序
package cn.tedu.m5;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.FanoutExchange;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class Main {
public static void main(String[] args) {
SpringApplication.run(Main.class, args);
}
//路由模式
@Bean
public TopicExchange topicExchange() {
return new TopicExchange("topicc_logs");
}
}
生产者
package cn.tedu.m5;
import java.util.Scanner;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class Sender {
@Autowired
AmqpTemplate t;
public void send() {
while (true) {
System.out.println("输入:");
String s = new Scanner(System.in).nextLine();
System.out.println("输入key:");
String key = new Scanner(System.in).nextLine();
t.convertAndSend("topicc_logs", key, s);
}
}
}
消费者
package cn.tedu.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 Receive {
/**
* 定义随机队列(随机命名,非持久,排他,自动删除)
* 可定义 交换机(已在主程序定义,课省略)
* 绑定(将队列绑定至交换机)
* @param s
* @throws Exception
*/
//@QueueBinding进行绑定设置 value = @Queue,定义随机队列 exchange = @Exchange指定logs交换机
@RabbitListener(bindings = @QueueBinding(
value = @Queue,
exchange = @Exchange(name = "topicc_logs",declare = "false"),
key = {"*.orange.*"}))
public void receive1(String s) throws Exception {
System.out.println("receiver1 - 收到: "+s);
}
@RabbitListener(bindings = @QueueBinding(
value = @Queue,
exchange = @Exchange(name = "topicc_logs",declare = "false"),
key = {"*.*.rabbit","lazy.#"}))
public void receive2(String s) throws Exception {
System.out.println("receiver2 - 收到: "+s);
}
}
RPC异步调用
主程序中定义两个队列
- 发送调用信息的队列: rpc_queue
- 返回结果的队列: 随机命名
主程序
package cn.tedu.m6;
import java.util.UUID;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.FanoutExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class Main {
public static void main(String[] args) {
SpringApplication.run(Main.class, args);
}
//rpc
//发送调用信息的队列
@Bean
public Queue sendQueue() {
return new Queue("rpcc_queue",false);
}
//返回结果的队列(随机)
@Bean
public Queue rndQueue() {
return new Queue(UUID.randomUUID().toString(),false);
}
}
服务端
package cn.tedu.m6;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
@Component
public class RpcServer {
@RabbitListener(queues = "rpcc_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);
}
}
客户端
package cn.tedu.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("rpcc_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("\n\n"+correlationId+" - 收到: "+r);
}
}
Rabbitmq的六种工作模式(附代码)
最后
需要资料软件,解决问题可私信博主
更多参考精彩博文请看这里:RR-Shmily
喜欢博主的小伙伴可以加个关注、点个赞,欢迎评论哦,持续更新嘿嘿!