ActiveMQ 介紹
MQ (MessageQueue)中文稱消息隊列,用於消息接收和轉發的容器,可用於消息推送。Active MQ 是一個Java的開源消息系統。很好的支持了 JMS 規範。
ActiveMQ 安裝
這裏使用的Docker安裝 地址:docker安裝activemq
ActiveMQ 集成
在pom.xml中引入依賴
<!--ActiveMQ-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-activemq</artifactId>
</dependency>
在application.properties配置
###ActiveMQ 配置
spring.activemq.broker-url = tcp://localhost:61616
spring.activemq.in-memory = true
spring.activemq.pool.enable = false
spring.activemq.package.trust-all = true
ActiveMQ 使用
我們都知道QQ空間有一個發說說的功能,這裏有很多的用戶同一時刻會發送大量的說說,這樣我們如果採用同步的方式,每一個用戶都佔用一條線程,那麼會導致系統性能大幅度降低。這樣就需要我們的ActiveMQ來進行異步消費抵抗高使用量的衝擊。
設計一個可以實現異步消費的生產者和消費者模型
消費者
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;
/**
* 描述:消費者
* @author wangyu
* @date 2019/5/16
*/
@Component
public class Consumer {
@JmsListener(destination = "activemq.queue")
public void receiveQueue(String text) {
System.out.println("信息接受*** "+text+" ***成功");
}
}
@JmsListener(destination = “activemq.queue”) 監聽隊列信息
destination = “activemq.queue” :監聽的隊列名
生產者
import javax.jms.Destination;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
/**
* 描述:生產者
* @author wangyu
* @date 2019/5/15
*/
@Service
public class Producer {
@Resource
private JmsTemplate jmsTemplate ;
public void sendMessage(Destination destination, final String message) {
jmsTemplate.convertAndSend(destination,message);
}
}
生產者消費者模型測試
/**
* 描述:ActiveMQ 測試
*/
@Test
public void testActiveMQ() {
Destination destination =
new ActiveMQQueue("activemq.queue") ;
producer.sendMessage(destination,"ActiveMQ測試消息");
}
打印出如下結果:
信息接受*** ActiveMQ測試消息 ***成功
以QQ空間的數據庫簡單的操作測試ActiveMQ的使用
根據我們對插入數據的操作和生產者消費者的模型結合,就是將我們的設置說說內容的操作放到生產者中,而將保存的插入數據庫的操作放到消費者中。就可以達到異步插入的目的。