参考文章:https://blog.csdn.net/liuyuanq123/article/details/79109218
Spring与ActiveMQ的整合及用JmsTemplate发送消息
1.pom文件:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-activemq</artifactId>
</dependency>
<!--消息队列连接池-->
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-pool</artifactId>
</dependency>
</dependencies>
2.yml文件
activemq:
broker-url: tcp://192.168.25.129:61616
user: admin
password: admin
in-memory: true
send-timeout: 1000 # 等待消息发送响应的时间,设置为0等待永远
pool:
enabled: true
max-connections: 100 #连接池最大连接数
idle-timeout: 30000 #空闲的连接过期时间,默认为30秒
block-if-full: false #当连接请求和池满时是否阻塞。设置false会抛“JMSException异常”。
reconnect-on-exception: false #当有"JMSException"时尝试重新连接
maximum-active-session-per-connection: 500 #每个连接的有效会话的最大数目
expiry-timeout: 0
3.生产者Producer:
//发送mq消息
sendJmsMsg(ActiveMQDao.DownExcel_Task_Test, downExeclTask.getId());
@Autowired
private JmsTemplate jmsTemplate;
/**
* 发送消息给指定队列
* @param destinationName
* @param message
* @return
*/
public Boolean sendJmsMsg(String destinationName,Object message){
if(message == null){
return false;
}
String msg = CommonUtil.beanToString(message);
return this.sendJmsMsg(destinationName,msg);
}
/**
* 发送指定目标mq
* @param destinationName 目标名
* @param message 消息内容
* @return
*/
public Boolean sendJmsMsg(String destinationName, String message) {
try{
jmsTemplate.convertAndSend(destinationName, message);
return true;
} catch (Exception e){
e.printStackTrace();
return false;
}
}
4.消费者Consumer:
4.1)消费者监听队列接收消息(注解是队列名)
//接收mq消息
@JmsListener(destination = ActiveMQDao.DownExcel_Task_Test)
public void downExecl(Integer downExeclId){
System.out.println("接收到消息:" + downExeclId);
}
4.2)消费者手动接收消息(入参是队列名)
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Service;
import javax.jms.JMSException;
import javax.jms.TextMessage;
@Service
public class ConsumerService {
@Autowired
private JmsTemplate jmsTemplate;
public String receive(String destination) throws JMSException,NullPointerException {
TextMessage textMessage = (TextMessage) jmsTemplate.receive(destination);
String text = textMessage.getText();
System.out.println("从队列" + destination.toString() + "收到了消息:\t" + text);
return text;
}
}