原理:
消息生产者 -> 交换机 ->消息队列 -> 消息消费者
- 交换机(Exchanges)
- 消息队列(Quences)
- 交换机和消息队列 之间需要绑定 Bind
- 消息队列发消息给消息消费者,是通过TCP/IP 管道模式发送
创建交换机(Add exchange)
- name:起一个名字
- Type: direct单点模式、 fanout全部发送、 topic匹配模式
- Durability : durable持久模式,一般选这个
创建队列(Addqueue)
- Name队列名字
- Durability:同上
绑定:
- 点击交换机
- To queue 发送给对应的队列
- Routing key 跟发送消息的文章绑定,一会发送消息就要用到这个
- 绑定单点direct交换机
- 绑定全部发送交换机
- 绑定匹配模式交换机
发送消息:
- 使用单点交换机发送:
结论:使用了单点模式发送,一次只有一个队列接收到了消息。
- 使用全部发送交换机发送:
结论:funout类型会全部发送,不会去匹配路由routing key. - 使用匹配模式交换机发送:
结论:topic 只有和Routing key 匹配上的进行了消息发送。
JAVA实战
pom
<!-- mq -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
application.properties
#rabbirmq
spring.rabbitmq.host=192.168.3.67
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
测试:
@Test
void contextLoads() {
Employee employee = new Employee();
employee.setEid(102);
employee.seteJob(100);
employee.seteName("小柯");
employee.setUpdateDate(new Date());
employee.setDepartmentDid(9);
employee.seteEmail("123456@qq.com");
rabbitTemplate.convertAndSend("exchange.topic","text.exe", employee);
}
employee需要序列化
结果:
原因:redis默认的是序列化,我们想在rabbit中查看需要转化为json
增加json转化器配置
@Configuration
public class MyAMQPConfig {
@Bean
public MessageConverter messageConverter(){
return new Jackson2JsonMessageConverter();
}
}
结果:
监听接收结果: @EnableRabbit 和 @RabbitListener 监听消息队列的内容
配置serviceImpl
@Service
public class RabbitListenerServiceImpl implements RabbitListenerService {
@Override
@RabbitListener(queues = "qwe")
public Employee getEmp(Employee employee) {
System.out.println(employee);
return null;
}
@RabbitListener(queues = "one.emps")
public void receive(Message message){
System.out.println("--------------------------------------------------------/n" + message.getBody() + "----------------" + message.getMessageProperties());
}
}
@SpringBootApplication
@MapperScan("com.redis.mapper")
@EnableRabbit
public class SpringbootRedisApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootRedisApplication.class, args);
}
}