为什么需要使用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);
}
}