1.导入ActiveMQ坐标
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-all</artifactId>
<version>5.14.0</version>
</dependency>
<!-- ActiveMQ的启动器 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-activemq</artifactId>
</dependency>
2.配置yml
spring.activemq.broker-url=tcp://127.0.0.1:61616
spring.activemq.in-memory=false
spring.activemq.password=admin
spring.activemq.user=admin
2.编写生产者配置类
/**
* 由于queue队列的名字是用户自己定义的,所以我们在这个配置文件中,只需要给定queue的名字就ok了
* @return
*/
@Configuration
public class ActiveMQConfig {
/**
* 队列模式
*/
@Bean
public Queue createQueue(){
return new ActiveMQQueue("com.zhongxia.email");
}
/**
*广播模式
*/
@Bean
public Topic createTopic(){
return new ActiveMQTopic("com.zhongxia.login");
}
}
3.编写消费者配置类
这里配置类都是一样的保证队列的名称要一致
/**
* 由于queue队列的名字是用户自己定义的,所以我们在这个配置文件中,只需要给定queue的名字就ok了
* @return
*/
@Configuration
public class ActiveMQConfig {
/**
* 队列模式
*/
@Bean
public Queue createQueue(){
return new ActiveMQQueue("com.zhongxia.email");
}
/**
*广播模式
*/
@Bean
public Topic createTopic(){
return new ActiveMQTopic("com.zhongxia.login");
}
}
4.生产者
@Autowired
private JmsMessagingTemplate jmsMessagingTemplate;
/**
* 发送短信,使用MQ
* @param phone
* @return
* @throws JMSException
*/
@GetMapping("/sendSMS/{phone}")
public ResponseEntity<Void> login(@PathVariable String phone) throws JMSException {
String number = GetRandomCodeUtil.getNumber();
//将验证码保存如redis中
redisTemplate.opsForValue().set(phone,number);
System.err.println(number);
//将电话和验证码放入MQ进行监听
ActiveMQMapMessage mapMessage = new ActiveMQMapMessage();
mapMessage.setString("phone",phone);
mapMessage.setString("code",number);
jmsMessagingTemplate.convertAndSend(queue,mapMessage);
return new ResponseEntity<>(HttpStatus.OK);
}
5.消费者
@Component
public class sendSMS {
@JmsListener(destination = "com.zhongxia.email") //保证这个destination 值和配置类队列名车一致
public void recevie(Message message) throws Exception{
MapMessage mapMessage = (MapMessage)message;
String telephone = mapMessage.getString("phone");
String code = mapMessage.getString("code");
// 调用SmsUtil
SmsUtil.sendSms(telephone,code);
System.out.println("ok");
}
}
6.查看消息消费情况
http://localhost:8161/
用户名密码默认都是admin