一、环境准备
RabbitMQ 3.7.4
SpringBoot 1.5.10.RELEASE
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
1
2
3
4
application.yml
spring:
rabbitmq:
host: 192.168.239.128
port: 5672
# username: test
# password: 123456
# virtual-host: /vhost_test
# publisher-confirms: true
1
2
3
4
5
6
7
8
二、简单队列
RabbitMQConfiguration.java 声明队列
package cn.saytime.config;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class RabbitMQConfiguration {
private static final String QUEUE_SIMPLE_NAME = "test_simple_queue";
@Bean
public Queue queue(){
return new Queue(QUEUE_SIMPLE_NAME, false, false, false, null);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
消费者
package cn.saytime.listener.simple;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
/**
* 消费者
*/
@RabbitListener(queues = "test_simple_queue")
@Component
public class SimpleRecv {
@RabbitHandler
public void process(String message) {
System.out.println("[x] rev : " + message);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
测试生产者
package cn.saytime;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class RabbitMQApplicationTests {
@Autowired
private AmqpTemplate amqpTemplate;
@Test
public void testSimpleQueue() {
String message = "Hello RabbitMQ !";
amqpTemplate.convertAndSend("test_simple_queue", message);
System.out.println("[x] send " + message + " ok");
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
执行test:
[x] send Hello RabbitMQ ! ok
[x] rev : Hello RabbitMQ !
1
2
三、工作队列
However, “Fair dispatch” is the default configuration for spring-amqp
公平分发模式在Spring-amqp中是默认的,这种