1. 程式人生 > >RabbitMq整合SpringBoot使用方法

RabbitMq整合SpringBoot使用方法

整合方法詳見:

整合好之後,開啟 http://localhost:15672,開啟rabbitMq。

使用方法:

1.定義一個Config類,用於定義Queue和Exchanger,然後將這2個類繫結起來,用於傳送檔案。

@Configuration
public class FanoutRabbitConfig {
    /**
     * 1.定義一個Queue,然後定義一個Exchange,繫結Queue和Exchange,即可實現傳送、接收
     * 2.接收類需要定義一個Listener,用於監聽傳送的相應訊息
     * @return
     */

    @Bean
    public Queue AMessage() {
        return new Queue("fanout.A");
    }

    @Bean
    public Queue BMessage() {
        return new Queue("fanout.B");
    }

    @Bean
    public Queue CMessage() {
        return new Queue("fanout.C");
    }

    @Bean
    FanoutExchange fanoutExchange() {
        return new FanoutExchange("fanoutExchange");
    }

    @Bean
    Binding bindingExchangeA(Queue AMessage,FanoutExchange fanoutExchange) {
        return BindingBuilder.bind(AMessage).to(fanoutExchange);
    }

    @Bean
    Binding bindingExchangeB(Queue BMessage, FanoutExchange fanoutExchange) {
        return BindingBuilder.bind(BMessage).to(fanoutExchange);
    }

    @Bean
    Binding bindingExchangeC(Queue CMessage, FanoutExchange fanoutExchange) {
        return BindingBuilder.bind(CMessage).to(fanoutExchange);
    }

}

2.定義Sender類,用於編輯報文內容,並使用AmqpTemplate的convertAndSend方法傳送報文。值得注意的是:convertAndSend(“fanoutExchange”,"", context)方法中,fanoutExchange要和FanoutRabbitConfig中定義的FanoutExchange名稱完全一致。

@Component
public class FanoutSender {

	@Autowired
	private AmqpTemplate rabbitTemplate;

	public void send() {
		String context = "hi, fanout msg ";
		System.out.println("Sender : " + context);
		this.rabbitTemplate.convertAndSend("fanoutExchange","", context);
	}

}

3.定義Receiver類,用與根據註冊在Config中的報文名稱接收報文內容。這裡需要定義Listener,@RabbitListener(queues = “fanout.A”),其中,fanout.A要在Config類中定義。

@Component
@RabbitListener(queues = "fanout.A")
public class FanoutReceiverA {

    @RabbitHandler
    public void process(String message) {
        System.out.println("fanout Receiver A  : " + message);
    }

}

4.編寫test類。

@RunWith(SpringRunner.class)
@SpringBootTest
public class FanoutTest {

	@Autowired
	private FanoutSender sender;

	@Test
	public void fanoutSender() throws Exception {
		sender.send();
	}
}

控制檯列印如下:

Sender : hi, fanout msg 
2018-11-19 11:03:28.355  INFO 5528 --- [       Thread-3] s.c.a.AnnotationConfigApplicationContext : Closing org.spring[email protected]37883b97: startup date [Mon Nov 19 11:03:24 CST 2018]; root of context hierarchy
2018-11-19 11:03:28.355  INFO 5528 --- [       Thread-3] o.s.c.support.DefaultLifecycleProcessor  : Stopping beans in phase 2147483647
2018-11-19 11:03:28.385  INFO 5528 --- [       Thread-3] o.s.a.r.l.SimpleMessageListenerContainer : Waiting for workers to finish.
fanout Receiver C: hi, fanout msg 
fanout Receiver A  : hi, fanout msg 
fanout Receiver B: hi, fanout msg