spring单元测试下模拟rabbitmq的实现
程序员文章站
2024-02-22 16:49:52
gradle添加引用
compile 'org.springframework.boot:spring-boot-starter-amqp'
testc...
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协议的队列。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。