时间:2020-11-05 18:02:46 | 栏目:JAVA代码 | 点击:次
gradle添加引用
compile 'org.springframework.boot:spring-boot-starter-amqp' testCompile 'com.github.fridujo:rabbitmq-mock:1.0.10'
添加bean对象
/** * 模拟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协议的队列。