认清现实,放弃幻想,准备斗争
http://你自己虚拟机的位置:15672http://192.168.100.103:15672
创建用户 srbuser,配置管理员权限
创建虚拟机 /srbhost,在Set permission中为新建的用户分配访问虚拟机 /srbhost 和 / 的权限
srb下创建rabbit-mq模块
org.springframework.boot
spring-boot-starter-amqp
com.alibaba
fastjson
org.projectlombok
lombok
@Configuration
public class MQConfig {
@Bean
public MessageConverter messageConverter(){
//json字符串转换器
return new Jackson2JsonMessageConverter();
}
}
public class MQConst {
public static final String EXCHANGE_TOPIC_SMS = "exchange.topic.sms";//交换机
public static final String ROUTING_SMS_ITEM = "routing.sms.item";//路由
public static final String QUEUE_SMS_ITEM = "queue.sms.item";//消息队列
}
@Service
@Slf4j
public class MQService {
@Resource
private AmqpTemplate amqpTemplate;
/**
* 发送消息
* @param exchange 交换机
* @param routingKey 路由
* @param message 消息
*/
public boolean sendMessage(String exchange, String routingKey, Object message) {
log.info("发送消息...........");
amqpTemplate.convertAndSend(exchange, routingKey, message);
return true;
}
}
@Data
@ApiModel(description = "短信")
public class SmsDTO {
@ApiModelProperty(value = "手机号")
private String mobile;
@ApiModelProperty(value = "消息内容")
private String message;
}
com.atguigu
rabbit-mq
0.0.1-SNAPSHOT
#spring:
rabbitmq:
host: 192.168.100.103
port: 5672
virtual-host: /srbhost
username: srbuser
password: 123456
UserInfoService接口:
String getMobileByBindCode(String bindCode);
UserInfoServiceImpl实现:
@Override
public String getMobileByBindCode(String bindCode) {
QueryWrapper userInfoQueryWrapper = new QueryWrapper<>();
userInfoQueryWrapper.eq("bind_code", bindCode);
UserInfo userInfo = baseMapper.selectOne(userInfoQueryWrapper);
return userInfo.getMobile();
}
UserAccountServiceImpl 充值回调方法的最后添加发送消息的代码:
@Resource
private UserInfoService userInfoService;
@Resource
private MQService mqService;
@Transactional(rollbackFor = Exception.class)
@Override
public void notify(Map paramMap) {
log.info("充值成功:" + JSONObject.toJSONString(paramMap));
......
//发消息
log.info("发消息");
String mobile = userInfoService.getMobileByBindCode(bindCode);
SmsDTO smsDTO = new SmsDTO();
smsDTO.setMobile(mobile);
smsDTO.setMessage("充值成功");
mqService.sendMessage(MQConst.EXCHANGE_TOPIC_SMS, MQConst.ROUTING_SMS_ITEM, smsDTO);
}
com.atguigu
rabbit-mq
0.0.1-SNAPSHOT
#spring:
rabbitmq:
host: 192.168.100.103
port: 5672
virtual-host: /srbhost
username: srbuser
password: 123456
@Component
@Slf4j
public class SmsReceiver {
@Resource
private SmsService smsService;
@RabbitListener(bindings = @QueueBinding(
value = @Queue(value = MQConst.QUEUE_SMS_ITEM, durable = "true"),
exchange = @Exchange(value = MQConst.EXCHANGE_TOPIC_SMS),
key = {MQConst.ROUTING_SMS_ITEM}
))
public void send(SmsDTO smsDTO) throws IOException {
log.info("SmsReceiver 消息监听");
Map param = new HashMap<>();
param.put("code", smsDTO.getMessage());
smsService.send(smsDTO.getMobile(), SmsProperties.TEMPLATE_CODE, param);
}
}
山高路远,江湖再见