一. 一些基本概念
消息队列
RabbitMQ
RabbitMQ-简书
柯南君:看大数据时代下的IT架构(2)消息队列之RabbitMQ-基础概念详细介绍
AMQP
二.依赖和配置
引入rabbitmq相关依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
相关配置
spring.rabbitmq.host=localhost
spring.rabbitmq.port=5276
spring.rabbitmq.username=guest
speing.rabbitmq.password=guest
三、使用样例1(Direct Exchange)
配置Direct Exchange
@Configuration
public class RabbitDirectConfig {
public static final String DIRECTNAME = "yzh-direct";
@Bean
Queue queue(){return new Queue("hello-queue");}
@Bean
DirectExchange directExchange(){
return new DirectExchange(DIRECTNAME,true,false);
}
@Bean
Binding binding(){
return BindingBuilder.bind(queue()).to(directExchange()).with("direct");
}
}
配置消费者
@Component
public class DirectReceiver {
@RabbitListener(queues="hello-queue")
public void handler1(String msg){
System.out.println("DirectReceiver:handler1:" + msg);
}
}
测试
注入RabbitTemplate
来发送消息
@Autowired
RabbitTemplate rabbitTemplate;
@Test
void contextLoads() {
rabbitTemplate.convertAndSend("hello-queue","Hello yzh!");
}
启动项目,运行测试方法
四、使用样例2(Fanout Exchange)
配置Fanout Exchange
@Configuration
public class RabbitFanoutConfig() {
public static final String FanoutNAME = "yzh-fanout";
@Bean
FanoutExchange fanoutExchange(){
return new FanoutExchange(FanoutNAME,true,false)
}
@Bean
Queue queueOne(){return new Queue("queue-one");}
@Bean
Queue queueTwo(){return new Queue("queue-two");}
@Bean
Binding bindingOne(){
return new BindingBuilder.bind(queueOne()).to(fanoutExchange());
}
@Bean
Binding bindingTwo(){
return new BindingBuilder.bind(queueTwo()).to(fanoutExchange());
}
}
配置消费者
@Component
public class FanoutReceiver{
@RabbitListener(queues = "queue-one")
public void handler1(String msg){
System.out.println("FanoutReceiver:handler1:" + msg);
}
@RabbitListener(queues = "queue-two")
public void handler2(String msg){
System.out.println("FanoutReceiver:handler2:" + msg);
}
}
测试
@Test
void test1(){
rabbitTemplate.convertAndSend(RabbitFanoutConfig.FANOUTNAME,null,"Hello yzh!哈哈哈");
}