1.引入依赖
新建一个工程,引入如下以来
<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>
2.创建MQConfig
该配置类是将消息序列化为json格式
@Configuration public class MQConfig { @Bean public MessageConverter messageConverter(){ //json字符串转换器 return new Jackson2JsonMessageConverter(); } }
3.创建MQConst
在这里定义一些发送消息要用到的一些常量,比如交换机、路由和队列
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";//消息队列 }
4.创建MQService
这个方法是rabbitmq为我们发消息的核心方法
@Service @Slf4j public class MQService { @Autowired 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; } }
5.在业务场景下发消息
5.1 rabbitmq在yml的配置
spring: rabbitmq: host: 39.99.33.230 port: 5672 username: guest password: guest
5.2 在业务pom引入rabbitMQ模块
<dependency> <groupId>com.gh</groupId> <artifactId>rabbit-mq</artifactId> <version>0.0.1-SNAPSHOT</version> </dependency>
5.3 消息体dto实现
@Data @ApiModel(description = "短信") public class SmsDto { @ApiModelProperty(value = "手机号") private String mobile; @ApiModelProperty(value = "消息内容") private String message; }
5.4 调取rabbitMQ发消息
例如,这里充值成功后会给用户发短信
if ("0001".equals(paramMap.get("resultCode"))) { log.info("验签成功,开始充值"); String result = userAccountService.notifyCharge(paramMap); //发消息 SmsDto smsDto = new SmsDto(); String bindCode = request.getParameter("bindCode"); String mobile = userInfoService.getMobileByBindCode(bindCode); smsDto.setMobile(mobile); smsDto.setMessage("充值成功"); mqService.sendMessage(MQConst.EXCHANGE_TOPIC_SMS, MQConst.ROUTING_SMS_ITEM, smsDto); return result; }
6.监听消息
6.1 配置rabbitmq
在短信模块进行yml的配置,和依赖的引入,同上
spring: rabbitmq: host: 39.99.33.230 port: 5672 username: guest password: guest
pml里引入如下依赖
<dependency> <groupId>com.gh</groupId> <artifactId>rabbit-mq</artifactId> <version>0.0.1-SNAPSHOT</version> </dependency>
6.2 消息监听与消费
通过注解RabbitListener指定队列、交换机和路由
@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("消息监听"); Map<String, Object> param = new HashMap<>(); param.put("code", smsDto.getMessage()); smsService.sendCode(param, smsDto.getMobile()); } }