1、在pom文件中引入對應jar包
<!--activeMQ start--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-activemq</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.apache.activemq</groupId> <artifactId>activemq-pool</artifactId> <!-- <version>5.7.0</version> --> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>5.0.7.RELEASE</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-test</artifactId> <version>2.0.3.RELEASE</version> </dependency> <!--activeMQ end-->
2、application.yml文件配置activemq;對於監聽Listener使用注解的形式
#activeMQ的配置 activemq: broker-url: tcp://localhost:61616 in-memory: true pool: enabled: false #如果此處設置為true,需要加如下的依賴包,否則會自動配置失敗,報JmsMessagingTemplate注入失敗
3、創建生產者類,生產者代碼如下:
/** * Created by Administrator on 2018/7/27. */ @RunWith(SpringRunner.class) @SpringBootTest public class SpringbootJmsApplicationTests { @Test public void contextLoads() throws InterruptedException, JMSException { Destination destination = new ActiveMQQueue("queue_demo"); //創建與JMS服務的連接:ConnectionFactory被管理的對象,由客戶端創建,用來創建一個連接對象 ConnectionFactory connectionfactory = new ActiveMQConnectionFactory("tcp://localhost:61616"); //獲取連接,connection一個到JMS系統提供者的活動連接 javax.jms.Connection connection = connectionfactory.createConnection(); //打開會話,一個單獨的發送和接受消息的線程上下文 Session session =connection.createSession(false,Session.AUTO_ACKNOWLEDGE ); Queue queue = new ActiveMQQueue("queue_demo"); MessageProducer msgProducer = session.createProducer(queue); Message msg = session.createTextMessage("文本1"); msgProducer.send(msg); System.out.println("文本消息已發送"); } }
4、編寫消費者代碼,代碼如下:
/** * Created by Administrator on 2018/7/27. */ @Component public class Consumer2 { // 使用JmsListener配置消費者監聽的隊列,其中text是接收到的消息 @JmsListener(destination = "queue_es") public void receiveQueue(String mapStr) { System.out.println("接受的消息:"+mapStr); } }
5、運行生產者(本處是test注解的測試代碼),直接運行,結果如下
發送端:
接收端:
ps:如果想設置為獨占消息消費模式,只需將消費者的代碼@JmsListener注解處修改為如下代碼:
@JmsListener(destination = "queue_es?consumer.exclusive=true")
就可以設置此消費者為獨占消息消費模式,隊列里的任務會玩先后順序被這個消費者處理掉