环境信息

JDK 版本 :1.7

RabbiMQ 服务端版本:3.8.8

erlang版本:Erlang 23.3.4.7

DIRECT 交换机:如果路由键匹配的话消息就被投递到对应的队列中

一、maven 依赖文件

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.3.19.RELEASE</version>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>1.7.21</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.1.7</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.19.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.amqp</groupId>
<artifactId>spring-rabbit</artifactId>
<version>1.7.10.RELEASE</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>

二、使用步骤

1. 消息生产者

package com.julong.producer;

import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;


/**
* 直连模式服务端启动
* @author julong
* @date 2022年1月20日 下午9:46:40
* @desc
*/
public class SpringApplicationProducerMain {
public static void main( String[] args ) {
ApplicationContext context = new FileSystemXmlApplicationContext("classpath:applicationContext-producer.xml");
CachingConnectionFactory factory = (CachingConnectionFactory) context.getBean("connectionFactory");
System.out.println("rabbitmq连接信息"+factory.toString());
RabbitAdmin rabbitAdmin = (RabbitAdmin) context.getBean("rabbitAdmin");
System.out.println("rabbitAdmin管理信息"+rabbitAdmin);
RabbitTemplate rabbitTemplate = (RabbitTemplate) context.getBean("rabbitTemplate");
System.out.println("rabbitTemplate模板信息"+rabbitTemplate);
for (int i = 0; i < 10; i++) {
rabbitTemplate.convertAndSend("spring-test-direct-queue","spring to hello rabbitmq!"+System.currentTimeMillis());
System.out.println("消息发送成功");
}

}
}

 生产者配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:rabbit="http://www.springframework.org/schema/rabbit"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/rabbit
http://www.springframework.org/schema/rabbit/spring-rabbit.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
<description>rabbitmq版配置</description>

<!-- 连接方式二 配置连接
id : 编号
host: 连接地址
port: 端口
username: 连接名称
password: 密码
virtual-host: 虚拟主机
connection-limit:最大连接数
cache-mode 缓存类型
-->
<rabbit:connection-factory id="connectionFactory"
host="192.168.10.222" port="5672"
username="julong" password="julong"
virtual-host="/"
connection-limit="25" cache-mode="CHANNEL" />


<!-- 通过指定下面的admin信息,当前producer中的exchange和queue会在rabbitmq服务器上自动生成
id: 编号
connection-factory: 连接工厂
auto-startup:是否自动启动
-->
<rabbit:admin id="rabbitAdmin" connection-factory="connectionFactory" auto-startup="true" />

<!-- 创建队列
id: 编号
name:队列名称
auto-delete:是否自动删除
durable:是否持久化
-->
<rabbit:queue id="springTestQueue" name="spring-test-direct-queue" auto-delete="false" durable="true" declared-by="rabbitAdmin" />

<!-- 绑定交换机
id: 交换机名称
name:交换机名称
-->
<rabbit:direct-exchange id="directExchange" name="spring-test-direct-exchange" auto-delete="true" declared-by="rabbitAdmin">
<rabbit:bindings>
<!-- 绑定交换机
queue:队列名称
key:路由键
-->
<rabbit:binding queue="spring-test-direct-queue" key="spring-test-direct-queue" />
</rabbit:bindings>
</rabbit:direct-exchange>

<!-- 定义消息接收发送模板类
id:编号标识
connection-factory:连接工厂
exchange:交换机
-->
<rabbit:template id="rabbitTemplate" connection-factory="connectionFactory" exchange="spring-test-direct-exchange" />



</beans>

2.消息消费者

package com.julong.consumer;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;


/**
* 直连模式客户端启动
* @author julong
* @date 2022年1月20日 下午9:46:40
* @desc
*/
public class SpringApplicationConsumerMain {
public static void main( String[] args ) {
ApplicationContext context = new FileSystemXmlApplicationContext("classpath:applicationContext-consumer.xml");
System.out.println(context.getApplicationName());
}
}

消费者配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:rabbit="http://www.springframework.org/schema/rabbit"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/rabbit
http://www.springframework.org/schema/rabbit/spring-rabbit.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
<description>rabbitmq版配置</description>

<!-- 连接方式二 配置连接
id : 编号
host: 连接地址
port: 端口
username: 连接名称
password: 密码
virtual-host: 虚拟主机
connection-limit:最大连接数
cache-mode 缓存类型
-->
<rabbit:connection-factory id="connectionFactory"
host="192.168.10.222" port="5672"
username="julong" password="julong"
virtual-host="/"
connection-limit="25" cache-mode="CHANNEL" />


<!-- 通过指定下面的admin信息,当前producer中的exchange和queue会在rabbitmq服务器上自动生成
id: 编号
connection-factory: 连接工厂
auto-startup:是否自动启动
-->
<rabbit:admin id="rabbitAdmin" connection-factory="connectionFactory" auto-startup="true" />

<!-- 创建队列
id: 编号
name:队列名称
auto-delete:是否自动删除
durable:是否持久化
-->
<rabbit:queue id="springTestQueue" name="spring-test-direct-queue" auto-delete="false" durable="true" declared-by="rabbitAdmin" />

<!-- 绑定交换机
id: 交换机名称
name: 交换机名称
auto-delete: 自定删除
-->
<rabbit:direct-exchange id="directExchange" name="spring-test-direct-exchange" auto-delete="true" declared-by="rabbitAdmin">
<rabbit:bindings>
<!-- 绑定交换机
queue:队列名称
key:路由键
-->
<rabbit:binding queue="spring-test-direct-queue" key="spring-test-direct-queue" />
</rabbit:bindings>
</rabbit:direct-exchange>

<!-- 定义消息接收发送模板类
id:编号标识
connection-factory:连接工厂
exchange:交换机
-->
<rabbit:template id="rabbitmqTemplate" connection-factory="connectionFactory" exchange="spring-test-direct-exchange" />


<bean id="consumerService" class="com.julong.consumer.service.impl.ConsumerServiceImpl"></bean>

<!--监听方法 -->
<rabbit:listener-container connection-factory="connectionFactory">
<rabbit:listener queues="spring-test-direct-queue" ref="consumerService" />
</rabbit:listener-container>

</beans>

 ConsumerService 类

package com.julong.consumer.service;

import org.springframework.amqp.core.MessageListener;

public interface ConsumerService extends MessageListener {

}

ConsumerServiceImpl 类

package com.julong.consumer.service.impl;

import java.io.UnsupportedEncodingException;

import org.springframework.amqp.core.Message;

import com.julong.consumer.service.ConsumerService;

/**
* 客户端监听的方法
* @author julong
* @date 2022年1月20日 下午10:43:20
* @desc
*/
public class ConsumerServiceImpl implements ConsumerService{

@Override
public void onMessage(Message message) {
// TODO Auto-generated method stub
try {
System.out.println("接收到的消息是:"+new String(message.getBody(), "utf-8"));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}



}

结果

服务端:

15:06:02.774 [main] TRACE o.s.a.r.c.CachingConnectionFactory - Cached Rabbit Channel: AMQChannel(amqp://julong@192.168.10.222:5672/,1), conn: Proxy@2ef3eef9 Shared Rabbit Connection: SimpleConnection@c33b74f [delegate=amqp://julong@192.168.10.222:5672/, localPort= 52406] retrieved from cache
15:06:02.774 [main] TRACE o.s.a.r.c.CachingConnectionFactory - AMQChannel(amqp://julong@192.168.10.222:5672/,1) channel.isOpen()
15:06:02.784 [main] TRACE o.s.a.r.c.CachingConnectionFactory - Found cached Rabbit Channel: Cached Rabbit Channel: AMQChannel(amqp://julong@192.168.10.222:5672/,1), conn: Proxy@2ef3eef9 Shared Rabbit Connection: SimpleConnection@c33b74f [delegate=amqp://julong@192.168.10.222:5672/, localPort= 52406]
15:06:02.784 [main] DEBUG o.s.amqp.rabbit.core.RabbitTemplate - Executing callback on RabbitMQ Channel: Cached Rabbit Channel: AMQChannel(amqp://julong@192.168.10.222:5672/,1), conn: Proxy@2ef3eef9 Shared Rabbit Connection: SimpleConnection@c33b74f [delegate=amqp://julong@192.168.10.222:5672/, localPort= 52406]
15:06:02.784 [main] DEBUG o.s.amqp.rabbit.core.RabbitTemplate - Publishing message on exchange [spring-test-direct-exchange], routingKey = [spring-test-direct-queue]
15:06:02.784 [main] TRACE o.s.a.r.c.CachingConnectionFactory - AMQChannel(amqp://julong@192.168.10.222:5672/,1) channel.basicPublish([spring-test-direct-exchange, spring-test-direct-queue, false, #contentHeader<basic>(content-type=text/plain, content-encoding=UTF-8, headers={}, delivery-mode=2, priority=0, correlation-id=null, reply-to=null, expiration=null, message-id=null, timestamp=null, type=null, user-id=null, app-id=null, cluster-id=null), [B@6356695f])
15:06:02.784 [main] TRACE o.s.a.r.c.CachingConnectionFactory - AMQChannel(amqp://julong@192.168.10.222:5672/,1) channel.close()
15:06:02.784 [main] TRACE o.s.a.r.c.CachingConnectionFactory - Returning cached Channel: AMQChannel(amqp://julong@192.168.10.222:5672/,1)
消息发送成功
15:06:02.784 [main] TRACE o.s.a.r.c.CachingConnectionFactory - Cached Rabbit Channel: AMQChannel(amqp://julong@192.168.10.222:5672/,1), conn: Proxy@2ef3eef9 Shared Rabbit Connection: SimpleConnection@c33b74f [delegate=amqp://julong@192.168.10.222:5672/, localPort= 52406] retrieved from cache
15:06:02.784 [main] TRACE o.s.a.r.c.CachingConnectionFactory - AMQChannel(amqp://julong@192.168.10.222:5672/,1) channel.isOpen()
15:06:02.784 [main] TRACE o.s.a.r.c.CachingConnectionFactory - Found cached Rabbit Channel: Cached Rabbit Channel: AMQChannel(amqp://julong@192.168.10.222:5672/,1), conn: Proxy@2ef3eef9 Shared Rabbit Connection: SimpleConnection@c33b74f [delegate=amqp://julong@192.168.10.222:5672/, localPort= 52406]
15:06:02.784 [main] DEBUG o.s.amqp.rabbit.core.RabbitTemplate - Executing callback on RabbitMQ Channel: Cached Rabbit Channel: AMQChannel(amqp://julong@192.168.10.222:5672/,1), conn: Proxy@2ef3eef9 Shared Rabbit Connection: SimpleConnection@c33b74f [delegate=amqp://julong@192.168.10.222:5672/, localPort= 52406]
15:06:02.784 [main] DEBUG o.s.amqp.rabbit.core.RabbitTemplate - Publishing message on exchange [spring-test-direct-exchange], routingKey = [spring-test-direct-queue]
15:06:02.784 [main] TRACE o.s.a.r.c.CachingConnectionFactory - AMQChannel(amqp://julong@192.168.10.222:5672/,1) channel.basicPublish([spring-test-direct-exchange, spring-test-direct-queue, false, #contentHeader<basic>(content-type=text/plain, content-encoding=UTF-8, headers={}, delivery-mode=2, priority=0, correlation-id=null, reply-to=null, expiration=null, message-id=null, timestamp=null, type=null, user-id=null, app-id=null, cluster-id=null), [B@4f18837a])
15:06:02.784 [main] TRACE o.s.a.r.c.CachingConnectionFactory - AMQChannel(amqp://julong@192.168.10.222:5672/,1) channel.close()
15:06:02.784 [main] TRACE o.s.a.r.c.CachingConnectionFactory - Returning cached Channel: AMQChannel(amqp://julong@192.168.10.222:5672/,1)
消息发送成功

客户端

接收到的消息是:spring to hello rabbitmq!1642921640255
15:07:20.295 [org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer#0-1] TRACE o.s.a.r.c.CachingConnectionFactory - AMQChannel(amqp://julong@192.168.10.222:5672/,1) channel.basicAck([10, true])
15:07:20.295 [org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer#0-1] TRACE o.s.a.r.l.SimpleMessageListenerContainer - Waiting for message from consumer.
15:07:20.295 [org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer#0-1] DEBUG o.s.a.r.l.BlockingQueueConsumer - Retrieving delivery for Consumer@59fd97a8: tags=[{amq.ctag-4fm8Adw8kjmkKvC06FbPig=spring-test-direct-queue}], channel=Cached Rabbit Channel: AMQChannel(amqp://julong@192.168.10.222:5672/,1), conn: Proxy@4b674b52 Shared Rabbit Connection: SimpleConnection@41e6199a [delegate=amqp://julong@192.168.10.222:5672/, localPort= 52407], acknowledgeMode=AUTO local queue size=0
15:07:21.305 [org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer#0-1] TRACE o.s.a.r.l.SimpleMessageListenerContainer - Waiting for message from consumer.
15:07:21.305 [org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer#0-1] DEBUG o.s.a.r.l.BlockingQueueConsumer - Retrieving delivery for Consumer@59fd97a8: tags=[{amq.ctag-4fm8Adw8kjmkKvC06FbPig=spring-test-direct-queue}], channel=Cached Rabbit Channel: AMQChannel(amqp://julong@192.168.10.222:5672/,1), conn: Proxy@4b674b52 Shared Rabbit Connection: SimpleConnection@41e6199a [delegate=amqp://julong@192.168.10.222:5672/, localPort= 52407], acknowledgeMode=AUTO local queue size=0
15:07:22.306 [org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer#0-1] TRACE o.s.a.r.l.SimpleMessageListenerContainer - Waiting for message from consumer.
15:07:22.306 [org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer#0-1] DEBUG o.s.a.r.l.BlockingQueueConsumer - Retrieving delivery for Consumer@59fd97a8: tags=[{amq.ctag-4fm8Adw8kjmkKvC06FbPig=spring-test-direct-queue}], channel=Cached Rabbit Channel: AMQChannel(amqp://julong@192.168.10.222:5672/,1), conn: Proxy@4b674b52 Shared Rabbit Connection: SimpleConnection@41e6199a [delegate=amqp://julong@192.168.10.222:5672/, localPort= 52407], acknowledgeMode=AUTO local queue size=0
15:07:23.307 [org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer#0-1] TRACE o.s.a.r.l.SimpleMessageListenerContainer - Waiting for message from consumer.
15:07:23.307 [org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer#0-1] DEBUG o.s.a.r.l.BlockingQueueConsumer - Retrieving delivery for Consumer@59fd97a8: tags=[{amq.ctag-4fm8Adw8kjmkKvC06FbPig=spring-test-direct-queue}], channel=Cached Rabbit Channel: AMQChannel(amqp://julong@192.168.10.222:5672/,1), conn: Proxy@4b674b52 Shared Rabbit Connection: SimpleConnection@41e6199a [delegate=amqp://julong@192.168.10.222:5672/, localPort= 52407], acknowledgeMode=AUTO local queue size=0
15:07:24.308 [org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer#0-1] TRACE o.s.a.r.l.SimpleMessageListenerContainer - Waiting for message from consumer.
15:07:24.308 [org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer#0-1] DEBUG o.s.a.r.l.BlockingQueueConsumer - Retrieving delivery for Consumer@59fd97a8: tags=[{amq.ctag-4fm8Adw8kjmkKvC06FbPig=spring-test-direct-queue}], channel=Cached Rabbit Channel: AMQChannel(amqp://julong@192.168.10.222:5672/,1), conn: Proxy@4b674b52 Shared Rabbit Connection: SimpleConnection@41e6199a [delegate=amqp://julong@192.168.10.222:5672/, localPort= 52407], acknowledgeMode=AUTO local queue size=0
15:07:25.309 [org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer#0-1] TRACE o.s.a.r.l.SimpleMessageListenerContainer - Waiting for message from consumer.
15:07:25.309 [org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer#0-1] DEBUG o.s.a.r.l.BlockingQueueConsumer - Retrieving delivery for Consumer@59fd97a8: tags=[{amq.ctag-4fm8Adw8kjmkKvC06FbPig=spring-test-direct-queue}], channel=Cached Rabbit Channel: AMQChannel(amqp://julong@192.168.10.222:5672/,1), conn: Proxy@4b674b52 Shared Rabbit Connection: SimpleConnection@41e6199a [delegate=amqp://julong@192.168.10.222:5672/, localPort= 52407], acknowledgeMode=AUTO local queue size=0