spring 整合jms
时间: 2023-10-21 17:05:45 浏览: 107
好的,关于spring整合jms的问题,您可以参考以下步骤进行操作:
1. 首先需要在pom.xml中引入相关依赖:
```
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jms</artifactId>
<version>5.2.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-all</artifactId>
<version>5.15.9</version>
</dependency>
```
2. 在spring配置文件中配置相关bean,例如:
```
<bean id="connectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
<property name="brokerURL" value="tcp://localhost:61616"/>
</bean>
<bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
<property name="connectionFactory" ref="connectionFactory"/>
</bean>
<bean id="messageListener" class="com.example.MyMessageListener"/>
<bean id="jmsContainer" class="org.springframework.jms.listener.DefaultMessageListenerContainer">
<property name="connectionFactory" ref="connectionFactory"/>
<property name="destination" ref="destination"/>
<property name="messageListener" ref="messageListener"/>
</bean>
<bean id="destination" class="org.apache.activemq.command.ActiveMQQueue">
<constructor-arg value="myQueue"/>
</bean>
```
3. 在代码中使用JmsTemplate发送和接收消息,例如:
```
@Autowired
private JmsTemplate jmsTemplate;
public void sendMessage(String message) {
jmsTemplate.send("myQueue", new MessageCreator() {
@Override
public Message createMessage(Session session) throws JMSException {
return session.createTextMessage(message);
}
});
}
@JmsListener(destination = "myQueue")
public void onMessage(Message message) {
if (message instanceof TextMessage) {
TextMessage textMessage = (TextMessage) message;
try {
String text = textMessage.getText();
System.out.println("Received message: " + text);
} catch (JMSException e) {
e.printStackTrace();
}
}
}
```
希望这些信息能够帮助您,还有什么其他问题需要我回答吗?
阅读全文