Add a reference gradle
compile 'org.springframework.boot:spring-boot-starter-amqp'
testCompile 'com.github.fridujo:rabbitmq-mock:1.0.10'
Add bean objects
/**
* 模拟rabbitmq.
*/
@ActiveProfiles("test")
@Component
public class RabbitMqMock {
@Bean
public ConnectionFactory connectionFactory() {
return new CachingConnectionFactory(MockConnectionFactoryFactory.build());
}
}
Add a test queue
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);
}
}
Summary: Through the above few lines of code, we can rabbitmq queue in a test environment to simulate, facilitated our test, and this method compared org.apache.qpid:qpid-broker:6.1.2
to more convenient package, of course, this package also supports other protocols queue qpid .