maven配置文件
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.amqp</groupId>
<artifactId>spring-rabbit</artifactId>
<version>2.2.7.RELEASE</version>
</dependency>
<!--slf4j core 使用slf4j必須添加-->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.27</version>
</dependency>
<!--slf4j 自带的简单日志实现 -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.7.27</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.22</version>
<scope>compile</scope>
</dependency>
</dependencies>
1、生产者
1.1、RabbitConfig配置文件类
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.net.URI;
@Configuration
public class RabbitConfig {
// 连接工厂
@Bean
public ConnectionFactory connectionFactory() {
ConnectionFactory factory = new CachingConnectionFactory(URI.create("amqp://root:123456@192.168.80.121:5672/%2f"));
return factory;
}
// RabbitTemplate
@Autowired
@Bean
public RabbitTemplate rabbitTemplate(ConnectionFactory factory) {
RabbitTemplate template = new RabbitTemplate(factory);
return template;
}
// RabbitAdmin
@Bean
@Autowired
public RabbitAdmin rabbitAdmin(ConnectionFactory factory) {
RabbitAdmin rabbitAdmin = new RabbitAdmin(factory);
return rabbitAdmin;
}
// Queue
@Bean
public Queue queue() {
Queue queue = QueueBuilder.nonDurable("queue.anno").build();
return queue;
}
// Exchange
@Bean
public Exchange exchange() {
FanoutExchange fanoutExchange = new FanoutExchange("ex.anno.fanout", false, false, null);
return fanoutExchange;
}
// Binding
@Bean
@Autowired
public Binding binding(Queue queue, Exchange exchange) {
// 创建一个绑定,不指定绑定的参数
Binding binding = BindingBuilder.bind(queue).to(exchange).with("key.anno").noargs();
return binding;
}
}
1.2、Producer
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.core.MessagePropertiesBuilder;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
import java.io.UnsupportedEncodingException;
public class ProducerApp {
public static void main(String[] args) throws UnsupportedEncodingException {
AbstractApplicationContext context = new AnnotationConfigApplicationContext(RabbitConfig.class);
RabbitTemplate template = context.getBean(RabbitTemplate.class);
// 发送消息
MessageProperties messageProperties = MessagePropertiesBuilder.
newInstance()
.setContentType(MessageProperties.CONTENT_TYPE_TEXT_PLAIN)
.setContentEncoding("gbk")
.setHeader("myKey", "myValue")
.build();
Message message = MessageBuilder.withBody("spring 注解方式".getBytes("gbk")).andProperties(messageProperties).build();
template.send("ex.anno.fanout","key.anno",message);
template.send("ex.anno.fanout","key.anno",message);
context.close();
}
}
2、拉消息模式
2.1、RabbitConfig
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.QueueBuilder;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.net.URI;
@Configuration
public class RabbitConfig {
@Bean
public ConnectionFactory connectionFactory() {
return new CachingConnectionFactory(URI.create("amqp://root:123456@192.168.80.121:5672/%2f"));
}
@Bean
@Autowired
public RabbitTemplate rabbitTemplate(ConnectionFactory factory) {
return new RabbitTemplate(factory);
}
@Bean
@Autowired
public RabbitAdmin rabbitAdmin(ConnectionFactory factory) {
return new RabbitAdmin(factory);
}
@Bean
public Queue queue() {
return QueueBuilder.nonDurable("queue.anno").build();
}
}
2.2、Consumer
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import java.io.UnsupportedEncodingException;
public class ConsumerApp {
public static void main(String[] args) throws UnsupportedEncodingException {
// 从指定类加载配置信息
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(RabbitConfig.class);
// 获取RabbitTemplate对象
RabbitTemplate template = context.getBean(RabbitTemplate.class);
// 接收消息
Message message = template.receive("queue.anno");
// 打印消息
System.out.println(new String(message.getBody(),message.getMessageProperties().getContentEncoding()));
// 关闭spring上下文对象
context.close();
}
}
3、监听器方式读取消息
3.1、RabbitConfig
import org.springframework.amqp.core.AcknowledgeMode;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.QueueBuilder;
import org.springframework.amqp.rabbit.annotation.EnableRabbit;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import java.net.URI;
@ComponentScan("com.lagou.rabbit.demo")
@Configuration
@EnableRabbit // xml中也可以使用<rabbit:annotation-driven/> 启用@RabbitListener注解
public class RabbitConfig {
@Bean
public ConnectionFactory connectionFactory() {
return new CachingConnectionFactory(URI.create("amqp://root:123456@192.168.80.121:5672/%2f"));
}
@Bean
@Autowired
public RabbitTemplate rabbitTemplate(ConnectionFactory factory) {
return new RabbitTemplate(factory);
}
@Bean
@Autowired
public RabbitAdmin rabbitAdmin(ConnectionFactory factory) {
return new RabbitAdmin(factory);
}
@Bean
public Queue queue() {
return QueueBuilder.nonDurable("queue.anno").build();
}
@Bean("rabbitListenerContainerFactory")
@Autowired
public SimpleRabbitListenerContainerFactory simpleRabbitListenerContainerFactory(ConnectionFactory connectionFactory) {
SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
factory.setConnectionFactory(connectionFactory);
factory.setAcknowledgeMode(AcknowledgeMode.AUTO);
factory.setConcurrentConsumers(10); // 设置并发监听器个数
factory.setMaxConcurrentConsumers(15);
factory.setBatchSize(10); // 按照批次进行消费
return factory;
}
}
3.2、定义监听器
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;
@Component
public class MyMessageListener {
/**
* com.rabbitmq.client.Channel 对象
* org.springframework.amqp.core.Message message 可以直接操作原生的AMQP消息
* org.springframework.messaging.Message to use the messaging abstraction counterpart
*
* @Payload 注解方法参数,该参数的值就是消息体
* @Header 注解方法参数,访问指定消息头字段的值
* @Headers 该注解的方法参数获取该消息的消息头的所有字段,参数类型对应于map集合
* MessageHeaders 参数类型,访问所有的消息头字段
* MessageHeaderAccessor or AmqpMessageHeaderAccessor 访问所有消息头字段
*/
/* @RabbitListener(queues = "queue.anno")
public void whenMessageCome(Message message) throws UnsupportedEncodingException {
System.out.println(new String(message.getBody(),message.getMessageProperties().getContentEncoding()));
} */
@RabbitListener(queues = "queue.anno")
public void whenMessageCome(@Payload String message) {
System.out.println(message);
}
}
3.3、Consumer
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class ConsumerListenerApp {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(RabbitConfig.class);
}
}