的中间件-RabbitMQ笔记(其中spring我改成了springboot)
// 导入Spring Boot和RabbitMQ的依赖
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.amqp.rabbit.annotation.EnableRabbit;
// 启用RabbitMQ功能
@EnableRabbit
@SpringBootApplication
public class RabbitMqApplication {
public static void main(String[] args) {
SpringApplication.run(RabbitMqApplication.class, args);
}
}
// 导入Spring AMQP和RabbitMQ的依赖
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
// 创建一个队列并定义绑定规则
@Component
public class RabbitMqConfig {
@Bean
public Queue simpleQueue() {
return new Queue("simple.queue", true);
}
@Bean
public Binding simpleQueueBinding(Queue simpleQueue) {
return BindingBuilder.bind(simpleQueue).to(simpleExchange());
}
}
// 接收消息的服务
@Component
public class ReceiverService {
@RabbitListener(queues = "simple.queue")
public void receiveMessage(String content) {
System.out.println("Received <" + content + ">");
}
}
这个示例展示了如何在Spring Boot应用中配置和使用RabbitMQ。首先,我们创建了一个Spring Boot应用并启用了RabbitMQ功能。然后,我们定义了一个配置类,在该类中创建了一个名为"simple.queue"的队列,并设置了交换器和路由键的绑定规则。最后,我们创建了一个服务类,使用@RabbitListener
注解来监听队列中的消息并打印出来。
评论已关闭