1.添加rabbitamq依赖
<!-- rabbitmq依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
2.在application.yml中添加对rabbimq的配置信息
rabbitmq:
addresses: ${RABBITMQ_HOST:127.0.0.1}:${RABBITMQ_PORT:5672}
username: root
password: 123456
virtual-host: host02
publisher-confirms: true
publisher-returns: true
3.生产者
import org.apache.log4j.Logger;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Date;
@RestController
public class ProducerController {
static Logger logger = Logger.getLogger(ProducerController.class);
@Autowired
private RabbitTemplate rabbitTemplate;
@GetMapping("/sendMessage")
public Object sendMessage() {
for (int i = 0; i < 100; i++) {
Date date = new Date();
String s = date.toString();
logger.info("send message {}"+s);
rabbitTemplate.convertAndSend("order-rabbit-exchange1", "order-rabbit-key1", s);
}
return "1111";
}
}
4.消费者
import org.apache.log4j.Logger;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.stereotype.Component;
@Component
public class Consumer {
static Logger logger = Logger.getLogger(Consumer.class);
// @RabbitListener(queues = "spring.rabbit.queue2") RabbitListener注解写在方法上
// 绑定监听,可以在未配置的情况下,在平台自动生成
@RabbitListener(bindings = @QueueBinding(
value = @Queue(value = "order-rabbit-queue1",
durable="true"),
exchange = @Exchange(value = "order-rabbit-exchange1",
durable="true", type= "topic",
ignoreDeclarationExceptions = "true"),
key = "order-rabbit-key1"
)
)
@RabbitHandler
public void consumeMessage(String message) {
System.out.println("consume message {}"+ message);
}
}
5.启动程序后,在RabbitMQ的客户端中,会发现多了一个队列,就是刚刚创建的队列
6.执行
IDEA 控制台会出现