compile 'org.springframework.boot:spring-boot-starter-amqp' testCompile 'com.github.fridujo:rabbitmq-mock:1.0.10'
/** * 模擬rabbitmq. */ @ActiveProfiles("test") @Component public class RabbitMqMock { @Bean public ConnectionFactory connectionFactory() { return new CachingConnectionFactory(MockConnectionFactoryFactory.build()); } }
public static final String LIND_EXCHANGE = "test.basic.exchange"; public static final String LIND_QUEUE_ROUTEKEY = "test.basic.*"; public static final String LIND_QUEUE_ROUTEKEY1 = "test.basic.a1"; public static final String LIND_QUEUE_ROUTEKEY2 = "test.basic.a2"; /** * 建立普通交換機. */ @Bean public TopicExchange lindExchange() { return (TopicExchange) ExchangeBuilder.topicExchange(LIND_EXCHANGE).durable(true) .build(); } @Bean public Queue key1() { return new Queue(LIND_QUEUE_ROUTEKEY1); } @Bean public Queue key2() { return new Queue(LIND_QUEUE_ROUTEKEY2); } /** * 綁定了routekey,一個routekey能夠被多個隊列綁定,相似於廣播. * * @return */ @Bean public Binding bindBuildersRouteKey1() { return BindingBuilder.bind(key1()) .to(lindExchange()) .with(LIND_QUEUE_ROUTEKEY); } /** * bind. * * @return */ @Bean public Binding bindBuildersRouteKey2() { return BindingBuilder.bind(key2()) .to(lindExchange()) .with(LIND_QUEUE_ROUTEKEY); } @Autowired private RabbitTemplate rabbitTemplate; /** * 發送撥打電話消息. */ public void publish(String message) { try { rabbitTemplate .convertAndSend(MqConfig.LIND_EXCHANGE, MqConfig.LIND_QUEUE_ROUTEKEY, message); } catch (Exception e) { e.printStackTrace(); } } /** * subscriber. * * @param data . */ @RabbitListener(queues = MqConfig.LIND_DEAD_QUEUE) public void customerSign(String data) { try { logger.info("從隊列拿到數據 :{}", data); } catch (Exception ex) { logger.error("簽約同步異常", ex); } }
總結:經過上面的幾行代碼,咱們能夠對rabbitmq隊列在測試環境中去模擬,方便了咱們的測試,而這種方法比org.apache.qpid:qpid-broker:6.1.2
這個包要方便的多,固然這個包也支持其它的qpid協議的隊列。git