ActiveMQ使用

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
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值