rabbitmq

一: 发送:rabbitSender.addSignWarnConfig(schoolDto);

二: 在 RabbitSender 文件中发送消息到mq中(在不同的服务中发送的是字符串):

import cn.hutool.json.JSONUtil;
@Autowired
private AmqpTemplate rabbitTemplate;

public void addSignWarnConfig(GxySchoolDto gxySchoolDto){
logger.info("修改的信息=="+gxySchoolDto);
rabbitTemplate.convertAndSend(Constant.RABBIT_CONFIG_SIGNWARN,JSONUtil.toJsonStr(gxySchoolDto));
}


public class Constant {
public static final String RABBIT_CONFIG_SIGNWARN="system.configSignWarn";
}


三: 在另一个服务中申明一个队列:
@Configuration
public class RabbitConfig {
@Bean
public Queue updateWarnConfig() {
return new Queue(Constant.RABBIT_CONFIG_SIGNWARN);
}
}

四:接收方:
@Component
public class RabbitReceiver {
private static Logger logger = LoggerFactory.getLogger(RabbitReceiver.class);

@Autowired
private CommonSysWarningService commonSysWarningService;

//修改考勤告警配置
@RabbitListener(queues = Constant.RABBIT_CONFIG_SIGNWARN)
@RabbitHandler
public void setSignWarnConfig(Channel channel, Message message){
String jsonstr = new String(message.getBody());
boolean isok = false;
try {
logger.info("消费者===============start");
logger.info("jsonstr=="+jsonstr);
CommonSysWarningEntity sysWarningEntity = JSONUtil.toBean(jsonstr,CommonSysWarningEntity.class);
if(sysWarningEntity != null && !StringUtils.isEmpty(sysWarningEntity.getSchoolId())){
commonSysWarningService.saveBySchool(sysWarningEntity);
}
//手动ack确认
channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
isok=true;
}catch (Exception ex){
logger.error("jsonstr=="+jsonstr);
}finally {
if(!isok){
try{
//丢弃这条消息
channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
}catch (Exception e1){
e1.printStackTrace();
}
}
}
}
}
原文地址:https://www.cnblogs.com/z360519549/p/11580369.html