rabbitMQ 在 Spring 中的使用范例:
- 在 pom.xml 文件中添加依赖:
<dependency>
<groupId>org.springframework.amqp</groupId>
<artifactId>spring-rabbit</artifactId>
<version>2.2.4.RELEASE</version>
</dependency>
- 在配置文件 application.properties 中添加 RabbitMQ 的相关配置:
spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
- 在 Spring Boot 应用中创建一个 ConnectionFactory 对象:
@Configuration
public class RabbitMQConfig {
@Value("${spring.rabbitmq.host}")
String host;
@Value("${spring.rabbitmq.port}")
int port;
@Value("${spring.rabbitmq.username}")
String username;
@Value("${spring.rabbitmq.password}")
String password;
@Bean
public ConnectionFactory connectionFactory() {
CachingConnectionFactory connectionFactory = new CachingConnectionFactory(host, port);
connectionFactory.setUsername(username);
connectionFactory.setPassword(password);
return connectionFactory;
}
}
- 创建一个 RabbitTemplate 对象,用于发送和接收消息:
@Component
public class RabbitMQSender {
@Autowired
private RabbitTemplate rabbitTemplate;
public void send(String exchange, String routingKey, Object message) {
rabbitTemplate.convertAndSend(exchange, routingKey, message);
}
}
- 在消费者端,使用 @RabbitListener 注解来监听队列中的消息:
@Component
public class RabbitMQReceiver {
@RabbitListener(queues = "${spring.rabbitmq.queue}")
public void receive(String message) {
System.out.println("收到消息:" + message);
}
}