正文
小伙伴们,你们好呀,我是老寇!(如果能解决小伙伴们的问题,老寇不胜荣幸!)
话不多说,直接看图!!!
解决方案(见代码):
@Configuration @Data public class RocketMqProducerProperties { @Value("${rocket.name-server}") private String nameServer; @Value("${rocket.producer.group}") private String group; } @Configuration @Slf4j public class DefaultRocketMqProducerConfig { @Autowired private RocketMqProducerProperties producerProperties; /** * 创建普通消息发送者实例 * @return * @throws MQClientException */ @Bean @Primary public DefaultMQProducer defaultMQProducer() throws MQClientException { DefaultMQProducer producer = new DefaultMQProducer(producerProperties.getGroup()); producer.setNamesrvAddr(producerProperties.getNameServer()); producer.setVipChannelEnabled(false); producer.setRetryTimesWhenSendAsyncFailed(10); producer.start(); log.info("default producer创建成功:{},{}",producerProperties.getNameServer(),producerProperties.getGroup()); return producer; } }
调用代码
@Service @Slf4j public class RocketMqServiceImpl { @Autowired private DefaultMQProducer defaultMQProducer; public boolean sendMessage(Map<String, Object> dataMap) { Message message = new Message("laokou.queue", JSON.toJSONBytes(dataMap)); try { SendResult sendResult = defaultMQProducer.send(message); if (SendStatus.SEND_OK.equals(sendResult.getSendStatus())) { log.info("发送成功, sendResult:{}", JSON.toJSONString(sendResult)); return true; } } catch (MQClientException e) { e.printStackTrace(); log.error("消息发送失败, error:{}", e); } catch (RemotingException e) { e.printStackTrace(); log.error("消息发送失败, error:{}", e); } catch (MQBrokerException e) { e.printStackTrace(); log.error("消息发送失败, error:{}", e); } catch (InterruptedException e) { e.printStackTrace(); log.error("消息发送失败, error:{}", e); } finally { return false; } } }