第一步:創建Maven項目
Maven依賴:
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-activemq</artifactId>
<version>2.2.6.RELEASE</version>
</dependency>
<!--Spring事務處理-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jms</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-all</artifactId>
<version>5.15.12</version>
</dependency>
<!--消息隊列連接池-->
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-pool</artifactId>
<version>5.15.12</version>
</dependency>
application.yml:
server:
port: 80
servlet:
context-path: /am
spring:
activemq:
broker-url: tcp://hcmaster:61616 #ActiveMQ服務器地址及端口
user: admin
password: admin
close-timeout: 5000
send-timeout: 3000
# 下面五行配置加上程序報錯,程序啓動不起來
# in-memory: false # true表示使用內置的MQ,false表示連接服務器
# pool:
# enabled: true # true表示使用連接池,false表示每發送一條數據就創建一個連接
# max-connections: 10 #連接池最大連接數
# idle-timeout: 30000 #空閒的連接過期時間,默認爲30s
jms:
pub-sub-domain: false # 默認值false表示Queue,true表示Topic
queueName1: springboot-activemq-queue2
queueName2: springboot-activemq-queue2
# debug: true #顯示Debug信息
第二步:生產者
@Service
public class Producer3 {
@Autowired // 也可以注入JmsTemplate,JmsMessagingTemplate對JmsTemplate進行了封裝
private JmsMessagingTemplate jmsTemplate;
// 發送消息,destination是發送到的隊列,message是待發送的消息
public void sendMessage(Destination destination, final String message) {
jmsTemplate.convertAndSend(destination, message);
}
@JmsListener(destination="${queueName2}")
public void consumerMessage(String text){
System.out.println("從隊列收到的回覆報文爲:"+text);
}
}
第三步:消費者
@Component
public class Consumer3 {
@JmsListener(destination = "${queueName1}")
@SendTo("${queueName2}")
public String receiveQueue(String text) {
System.out.println("Consumer3收到的消息爲:" + text);
return "返回消息:" + text;
}
}
測試代碼
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootJmsApplicationTests {
@Value("${queueName1}")
private String queueName;
@Autowired
private Producer3 producer3;
@Test
public void contextLoads() {
Destination destination = new ActiveMQQueue(queueName);
producer3.sendMessage(destination, "請接收消息");
try {
System.in.read();
} catch (IOException e) {
e.printStackTrace();
}
}
}
結果: