第一步 引入依赖
org.springframework.boot
spring-boot-starter-amqp
第二步 配置文件中配置rabitmq的信息
spring:
# rabbitmq 的配置
rabbitmq:
host: localhost
port: 5672
username: heima
password: heima
virtual-host: /itcast
以上为公共配置 消费者和生产者都要添加
生产者配置交换机和队列 绑定交换机和队列
@Configuration
public class RabbitmqConfig {
public static final String EXCHANGE_NAME = "boot_topic_exchange";
public static final String QUEUE_NAME = "boot_topic_queue";
// 1.声明一个交换机
@Bean("bootExchange")
public Exchange bootExchange(){
return ExchangeBuilder.topicExchange(EXCHANGE_NAME).durable(true).build();
}
// 2.声明一个队列
@Bean("bootQueue")
public Queue bootQueue(){
return QueueBuilder.durable(QUEUE_NAME).build();
}
// 3.交换机和队列绑定
@Bean
public Binding bootBind(@Qualifier("bootQueue") Queue queue,@Qualifier("bootExchange") Exchange exchange){
return BindingBuilder.bind(queue).to(exchange).with("boot.#").noargs();
}
}
生产者 发送消息
@Service
public class SendRabbitMqServiceImpl implements SendRabbitMqService {
@Autowired
private RabbitTemplate rabbitTemplate;
@Override
public Result send() {
rabbitTemplate.convertAndSend(RabbitmqConfig.EXCHANGE_NAME,"boot.error","错误日志-------------->>>>>");
return Result.ok();
}
}
消费者
监听生产者 的消息
@Component
@Slf4j
public class ReceiveRabbitmq {
@RabbitListener(queues = RabbitmqConfig.QUEUE_NAME)
public void ReceiveRabbitmq(Message message){
log.info("boot_topic_queue队列中存储的消息>>>" + message);
}
}



