ActiveMQ使用


为什么需要使用MQ?

在日常我们使用一台服务器进行多个请求,多个请求同时进来,后进来的请求处于一个等待的状态,MQ的引用由此而来


MQ的优点?

1.系统解耦
当系统A需要去调用B下的内容,B需要经过B下其他C,D处理后返回A,B下面的服务A就不需要去管了。
2.异步调用
3.流量削峰


队列

每个消息有且只有一个消费者.
消费者和生产生没有时间上的关联性,无论生产者在消费者之前还是之后创建消息,消费者最终都可以消费.
消息被消费后,队列中将不会在存储该条消息.

主题

生产者将消息发布到topic,一个消息有多个消费者.
生产者和消费者有时间上的相关性,如果生产者先生产消息,消费者没有先开启那么这条消息是一条废消息.

实例代码

 <dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-activemq</artifactId>
</dependency>
spring.activemq.broker-url=tcp://192.168.234.128:61616
spring.activemq.user=admin
spring.activemq.password=admin
spring.jms.pub-sub-domain=false
# spring.jms.pub-sub-domain=true //true和false代表是主题还是队列
#自定义队列名称
myQueen=boot-active-mq
myTopic=boot-topic
 //消息队列
@Configuration
public class ConfigBean {

    //设置队列
    @Value("${myQueen}")
    private String muQueen;
    
    //设置主题
    @Value("${myTopic}")
    private String myTopic;

    //设置当前模式为队列
    @Bean
    public Queue queue(){
        return new ActiveMQQueue(muQueen);
    }

    //设计当前模式为主题
    @Bean
    public Topic topic(){
        return new ActiveMQTopic(myTopic);
    }
}
//生产者
@Component
public class ProducerMQ {

    @Resource
    private JmsMessagingTemplate jmsMessagingTemplate;

    @Autowired
    private Queue queue;
    @Autowired
    private Topic topic;

    public void produceMsg(){
        jmsMessagingTemplate.convertAndSend(queue,"hello producer");
    }

    //每3S发送一次消息队列
    @Scheduled(fixedDelay = 3000)
    public void produceMsgSend(){
        jmsMessagingTemplate.convertAndSend(queue,"hello producer");
    }
	
    //每3S发送一次主题信息
    @Scheduled(fixedDelay = 3000)
    public void produceMsgTopicSend(){
        System.out.println("执行了。。。。。");
        jmsMessagingTemplate.convertAndSend(topic,"topic");
    }

}
//消费者
@Component
public class Consumer {

    @JmsListener(destination = "${myQueen}")
    public void receiveMsg(TextMessage textMessage) throws JMSException {
        System.out.println("消费者收到的队列为"+textMessage.getText());
    }

    @JmsListener(destination = "${myTopic}")
    public void receiveTopic1(TextMessage textMessage) throws JMSException {
        System.out.println("消费者收到的主题为11:"+textMessage.getText());
    }

    @JmsListener(destination = "${myTopic}")
    public void receiveTopic2(TextMessage textMessage) throws JMSException {
        System.out.println("消费者收到的主题为22:"+textMessage.getText());
    }
}
@SpringBootApplication
@EnableJms
@EnableScheduling
public class ActivemqApplication {

    public static void main(String[] args) {
        SpringApplication.run(ActivemqApplication.class, args);
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值