1.第一步首先在maven中引入RabbitMQ的依赖关系
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
2.第一步消息配置
/** 消息发送 1.短信 2.站内信 **/
public static final String QUEUE_MSG_SEND = "msg:send";
/** 短信发送队列 */
public static final String QUEUE_MSG_SMS_SEND = "msg:sms:send";
/**
* 消息配置
* @author swt
*/
@Configuration
public class RabbitConfig {
/**
* 短信发送队列
* @return
*/
@Bean
public Queue smsQueue() {
return new Queue(QUEUE_MSG_SMS_SEND, true);
}
/**
* 消息发送队列(1.短信 2.站内信)
* @return
*/
@Bean
public Queue msgQueue() {
return new Queue(QUEUE_MSG_SEND, true);
}
}
3.第三步配置服务端
/**
* 消息管理(1.短信 2.站内信)
* @auther ywl
*/
@Component
@RabbitListener(queues = QUEUE_MSG_SEND)
public class MsgReceiver {
private Log log = LogFactory.getLog(MsgReceiver.class);
@Resource
private MsgService msgService;
@Resource
private MemberUserService memberUserService;
private ObjectMapper mapper = new ObjectMapper();
@RabbitHandler
public void process(Msg msg) {
try {
log.info("-----消息发送开始------");
log.info(mapper.writeValueAsString(msg));
msgService.sendMsg(msg);
log.info("-----消息发送结束------");
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
}
4.第四步配置消费端
@Resource
private AmqpTemplate amqpTemplate;
//添加资金账户支出变动消息队列
Msg msg = new Msg();
msg.setMemberId(trade.getMemberId());
msg.setType(cn.ug.msg.bean.status.CommonConstants.MsgType.ACCOUNT_PAY_CHANGE.getIndex());
Map<String, String> paramMap = new HashMap<>();
paramMap.put("date", UF.getFormatDate("MM月dd日", UF.getDateTime()));
paramMap.put("changeAmount", BigDecimalUtil.to2Point(trade.getAmount()).toString());
paramMap.put("amount", BigDecimalUtil.to2Point(fundAmount).toString());
msg.setParamMap(paramMap);
logger.info("-----消息-------"+paramMap.toString());
amqpTemplate.convertAndSend(QUEUE_MSG_SEND, msg);