//是一個運行器,註解了@RunWith就可以直接使用spring容器,直接使用@Test註解,不用啓動spring容器
//SpringRunner 繼承了SpringJUnit4ClassRunner,沒有擴展任何功能;使用前者,名字簡短而已。
@RunWith(SpringRunner.class)
//是SpringBoot自1.4.0版本開始引入的一個用於測試的註解
//SpringBootTest.WebEnvironment.RANDOM_PORT經常和測試類中@LocalServerPort一起在注入屬性時使用。會隨機生成一個端口號
@SpringBootTest(classes = WorkstackApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class RabbitMqTests {
private static final Logger logger = LoggerFactory.getLogger(RabbitMqTests.class);
@Autowired
private RabbitTemplate rabbitTemplate;
@Test
public void testSendMessage() {
logger.info("手動創建rabbitTemplate");
/**
CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
connectionFactory.setAddresses("127.0.0.1:5672");
connectionFactory.setUsername("admin");
connectionFactory.setPassword("adminadmin");
connectionFactory.setVirtualHost("/");
// 如果需要confirm則設置爲true
connectionFactory.setPublisherConfirms(true);
RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
//rabbitTemplate.setConfirmCallback(rabbitConfirmCallback);
rabbitTemplate.setMandatory(true);
//rabbitTemplate.setReturnCallback(rabbitReturnCallback);
//使用單獨的發送連接,避免生產者由於各種原因阻塞而導致消費者同樣阻塞
rabbitTemplate.setUsePublisherConnection(true);
*/
logger.info("消息發送:");
// rabbitTemplate.setChannelTransacted(false);
// rabbitTemplate.setChannelTransacted(true);
// rabbitTemplate.send("", );
rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
System.out.println(" ID:" + correlationData);
if (ack) {//true表示消息發送成功
logger.info("消息發送成功");
} else {
logger.info("消息發送失敗:" + cause);
}
});
Map<String, Object> map = Maps.newHashMap();
map.put("key1","value1");
map.put("key2","value2");
rabbitTemplate.convertAndSend(
null,
"aa.message", "測試消息", msg -> {
MessageProperties properties = msg.getMessageProperties();
properties.setDeliveryMode(MessageDeliveryMode.PERSISTENT);
Map<String, Object> headers = msg.getMessageProperties().getHeaders();
headers.putAll(map);
return msg;
}, new CorrelationData(UUID.randomUUID().toString())
);
}
}