在pom.xml文件中添加RabbitMQ的依赖:
org.springframework.boot spring-boot-starter-amqp
在application.properties或application.yml文件中添加RabbitMQ的连接信息:
spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
创建一个RabbitMQ配置类,在该类中配置RabbitMQ的Exchange、Queue、Binding等信息:
@Configuration
public class RabbitMQConfig {@Beanpublic Queue helloQueue() {return new Queue("hello");}@Beanpublic DirectExchange directExchange() {return new DirectExchange("directExchange");}@Beanpublic Binding binding() {return BindingBuilder.bind(helloQueue()).to(directExchange()).with("hello");}
}
创建一个生产者类,用于发送消息到RabbitMQ:
@Component
public class RabbitMQProducer {@Autowiredprivate AmqpTemplate amqpTemplate;public void send(String message) {amqpTemplate.convertAndSend("directExchange", "hello", message);}
}
创建一个消费者类,用于接收RabbitMQ发送的消息:
@Component
public class RabbitMQConsumer {@RabbitListener(queues = "hello")public void process(String message) {System.out.println("Received message: " + message);}
}
在需要发送消息的地方,注入RabbitMQProducer并调用send方法即可:
@RestController
public class TestController {@Autowiredprivate RabbitMQProducer rabbitMQProducer;@GetMapping("/send")public String send() {rabbitMQProducer.send("Hello, RabbitMQ!");return "Message sent";}
}
运行Spring Boot应用程序,并访问/send接口发送消息,可以在控制台中看到消费者打印出的消息。
以上是Spring Boot整合RabbitMQ并在项目中使用的步骤。需要注意的是,在项目中使用RabbitMQ时,需要注意消息的格式和编码方式。