Time: 2024-06-20 Thursday 11:28:01
Author: Jackasher
SpringAMQP
基于Spring
实现的MQ消息队列发送与接受,首先要配置MQ
的信息,端口,用户,密码,主机,和虚拟Host
,
1 2 3 4 5 6 7
| spring: rabbitmq: host: 127.0.0.1 port: 5672 username: itcast password: 123321 virtual-host: /
|
接下来是生产者,很简单,主要是rabbitTemplate
类,使用convertSend
方法传入交换机的名字和key
,以及消息
1 2 3 4 5
| public void fountSend2(){ String exchangeName = "itcast_direct"; String msg = "Hello everyone!!!"; rabbitTemplate.convertAndSend(exchangeName,"red",msg); }
|
那么这个交换机哪里来的,一种是Spring
的Bean
的配置,二是采用注解,首先是Bean
的配置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| @Bean public FanoutExchange fanoutExchange(){ return new FanoutExchange("itcast.fanout"); }
@Bean public Queue queue1(){ return new Queue("fanout.queue1"); } @Bean public Binding fanoutBinding1(Queue queue1, FanoutExchange fanoutExchange){ return BindingBuilder.bind(queue1).to(fanoutExchange); }
|
接下来是注解形式
1 2 3 4 5 6 7 8 9 10 11 12
| @RabbitListener(bindings = @QueueBinding( //创建队列 value = @Queue("direct_queue1"), //创建并绑定交换机和key exchange = @Exchange(name = "itcast_direct", type = ExchangeTypes.DIRECT), key = {"red","blue"} )) public void listenSimpleQueue5(String msg) throws InterruptedException { System.out.println("consumer5 has received:" + msg + LocalDateTime.now());
}
|