导入依赖
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-all</artifactId>
<version>5.9.0</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jms</artifactId>
<version>4.3.18.RELEASE</version>
</dependency>
配置application.xml
<!--JMS配置-->
<!--Activemq的连接工厂-->
<bean id="targetConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
<property name="brokerURL" value="tcp://127.0.0.1:61616" />
</bean>
<!--spring-JMS对Activemq的连接工厂进行封装-->
<bean id="JMSconnectionFactory" class="org.springframework.jms.connection.SingleConnectionFactory">
<property name="targetConnectionFactory" ref="targetConnectionFactory" />
</bean>
<!--消息目的地(队列模式)-->
<bean id="queueDestination" class="org.apache.activemq.command.ActiveMQQueue">
<constructor-arg value="SpringActiveMQMsg"/>
</bean>
<!--消息目的地(主题模式)-->
<bean id="topicDestination" class="org.apache.activemq.command.ActiveMQTopic">
<constructor-arg value="SpringActiveMQMsgTopic"/>
</bean>
<!--JMS模板,用于进行消息发送-->
<bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
<property name="connectionFactory" ref="JMSconnectionFactory"/>
</bean>
<!--配置消息监听器-->
<bean id="consumerMessageListener" class="com.scheduleserver.Listener.MyMessageListener"/>
<!--配置消息容器-->
<bean id ="jmsContainer" class="org.springframework.jms.listener.DefaultMessageListenerContainer">
<!--配置连接工厂-->
<property name="connectionFactory" ref="JMSconnectionFactory"/>
<!--配置监听的目的地-->
<property name="destination" ref="queueDestination"/>
<!--配置消息监听器-->
<property name="messageListener" ref="consumerMessageListener"/>
</bean>
生产者发送信息
@Autowired
private JmsTemplate jmsTemplate;
//可能存在多个目的地,所以用按名称注入
@Resource(name = "queueDestination")
private Destination destination;
//测试
@PostMapping("/test")
public ResponseObject test(@RequestParam String msg) {
jmsTemplate.send(destination , new MessageCreator() {
@Override
public Message createMessage(Session session) throws JMSException {
TextMessage textMessage = session.createTextMessage(msg);
return textMessage;
}
});
System.out.println("费哥爱你哦: " + msg);
return ResponseObject.generateSuccessResponse();
}
消费者接收信息
import javax.jms.JMSException;
import javax.jms.MessageListener;
import javax.jms.TextMessage;
public class MyMessageListener implements MessageListener {
@Override
public void onMessage(javax.jms.Message message) {
TextMessage tmes = (TextMessage) message;
try {
System.out.println(tmes.getText());
} catch (JMSException e) {
e.printStackTrace();
}
}
}
控制台输出:
费哥爱你哦: 自律使我自由!
自律使我自由!
总结
若想按主题发送消息,生产者和消费者的目标地址换成主题目标地址就行了。