目录
前言
本例子只是SpringBoot整合一下RabbitMQ,在此环境下如何去发送一个消息(至于produce有木有发送到RabbitMQ,以及consumer有木有成功的拿到消息,暂且不说,下回再讲)
具体步骤
环境准备
1、准备一个SpringBoot工程
此处不多说了,利用IDEA几步即可完成,大概结构如下(consumer包用来存消费端代码)
2、引入相关的jar包
为了方便直接利用Junit来搞了
<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>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
3、配置一下yml
spring:
application:
name: springboot-rabbitmq
rabbitmq:
host: localhost
port: 5672
username: guest
password: guest
virtual-host: /test #虚拟主机
各个模式发送消息
1、HelloWorld模式(简单队列)
特点:一个生产者对应一个消费者
消息生产端(produce):
@SpringBootTest(classes = SpringbootRabbitmqApplication.class)
@RunWith(SpringRunner.class)
class SpringbootRabbitmqApplicationTests {
//注入rabbitmqTemplate,用于操作rabbitmq相关的方法
@Autowired
private RabbitTemplate rabbitTemplate;
@Test
void test_helloworld() {
//MessageProperties是对消息的封装
Message message = new Message("大家好,我是hello world".getBytes(),new MessageProperties());
//MessageProperties 封装消息的一些属性,属性比较多,我这里只设置以下消息的持久化,PERSISTENT-持久化 NON_PERSISTENT-非持久化
message.getMessageProperties().setDeliveryMode(MessageDeliveryMode.PERSISTENT);
//发送消息 这种模式比较简单,hello_world可以理解为队列的名字,虽然木有指定交换机但是它默认是有个交换机的,名字也是hello_world
rabbitTemplate.convertAndSend("hello_world",message);
}
}
消息消费端(consumer):
观察控制台是否打印出消息内容
@Component
public class HelloWorldConsumer {
//@RabbitListener可以标记在类上,如果标记在类上,那么需要在方法上加@RabbitHandler
@RabbitListener(queuesToDeclare = @Queue(value = "hello_world")) //队列默认是持久化的,可以通过durable(是否持久化)和autoDelete(是否自动删除)去设置
public void receive(Message message){
//获取消息并且打印
String msg = new String(message.getBody());
System.out.println(msg);
}
}
2、Work模式
特点:一个生产者对应多个消费者,但是一条消息只能被一个消费者消费!!!(默认是平均消费的,例如发送10条消息,