SpringBoot整合RabbitMQ
依赖
compile 'org.springframework.boot:spring-boot-starter-amqp'
application.properties
配置关于RabbitMQ的连接和用户信息,在管理Rabbit管理页面中创建用户。
spring.application.name=rabbitmq-hello spring.rabbitmq.host=localhost spring.rabbitmq.port=5672 spring.rabbitmq.username=guest spring.rabbitmq.password=guest
spring.rabbitmq.virtual-host=/
spring.rabbitmq.connection-timeout=15000
#消费端配置
spring.rabbitmq.simple.concurrency=5
Sender
@Component
public class Sender {
@Autowired
private AmqpTemplate rabbitTemplate;
public void send() {
String context = "hello " + new Date();
System.out.println("Sender : " + context);
this.rabbitTemplate.convertAndSend("MyQueue", context);
}
}
Receiver
public class RabbitReceiver {
//构建和绑定Message
@RabbitListener(bindings = @QueueBinding(
value=@Queue(value="test-queue",durable = "true"),
exchange = @Exchange(name="test-exchange",durable = "true",type="topic"),
key = "test.*"
))
@RabbitHandler
public void process(@Payload Message m, @Headers Map<String,Object> header, Channel channel) throws IOException {
System.out.println("Receiver : " + m.getId());
Long tag = (Long) header.get(AmqpHeaders.DELIVERY_TAG);
channel.basicAck(tag,false
);
}
}
Test
@RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = HelloApplication.class) public class HelloApplicationTests { @Autowired private Sender sender; @Test public void hello() throws Exception { sender.send(); } }