核心业务10:整合rabbitmq
1.开启rabbitmq服务器
2.配置rabbit-mq模块
①引入依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>
②创建模块
package com.atguigu.srb.rabbitutil.config;
@Configuration
public class MQConfig {
@Bean
public MessageConverter messageConverter(){
return new Jackson2JsonMessageConverter();
}
}
package com.atguigu.srb.rabbitutil.constant;
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";
}
package com.atguigu.srb.rabbitutil.service;
@Service
@Slf4j
public class MQService {
@Resource
private AmqpTemplate amqpTemplate;
public boolean sendMessage(String exchange, String routingKey, Object message) {
log.info("发送消息...........");
amqpTemplate.convertAndSend(exchange, routingKey, message);
return true;
}
}
3.在service-base中创建vo
3.在service-base中创建vo
4.服务者与消费者
①业务
②sms微服务和core微服务配置
<!--rabbitmq消息队列-->
<dependency>
<groupId>com.atguigu</groupId>
<artifactId>rabbit-mq</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
#spring
rabbitmq:
host: localhost
port: 5672
username: guest
password: guest
③配置生产者
- 在充值回调结束后发送短信
com/atguigu/srb/core/service/impl/UserAccountServiceImpl.java
String mobile = userInfoService.getMobileByBindCode(bindCode);
SmsDTO smsDTO = new SmsDTO();
smsDTO.setMobile(mobile);
smsDTO.setMessage("6666");
mqService.sendMessage(
MQConst.EXCHANGE_TOPIC_SMS,
MQConst.ROUTING_SMS_ITEM,
smsDTO);
return "success";
④配置消费者
package com.atguigu.srb.sms.receiver;
import com.atguigu.srb.base.dto.SmsDTO;
import com.atguigu.srb.rabbitutil.constant.MQConst;
import com.atguigu.srb.sms.service.SmsService;
import com.atguigu.srb.sms.util.SmsProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.HashMap;
@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){
log.info("SmsReceiver消息监听。。。。");
HashMap<String, Object> param = new HashMap<>();
param.put("code",smsDTO.getMessage());
smsService.send(smsDTO.getMobile(), SmsProperties.TEMPLATE_CODE,param);
}
}
未更新