</bean>
4、配置destination;
<bean id="destination" class="org.apache.activemq.command.ActiveMQQueue">
<constructor-arg index="0" value="jms-test-queue" />
</bean>
5、配置监听,消费消息方自动接收消息;
<bean id="jmsContainer"
class="org.springframework.jms.listener.DefaultMessageListenerContainer">
<property name="connectionFactory" ref="connectionFactory" />
<property name="destination" ref="destination" />
<property name="messageListener" ref="getMessage" /> //自定义监听类,
<property name="sessionTransacted" value="true"/>
</bean>
以上为activeMQ在applicationContext.xml中的简单配置;以下说一下如何发送和接收消息;
使用注解方式将destination和jmsTemplate注入SendMessage类;
发送消息代码:
import javax.annotation.Resource;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.Session;
import javax.jms.TextMessage;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service;
@Service("sendMessage")
public class SendMessage {
@Resource
private JmsTemplate jmsTemplate;
@Resource
private Destination destination;
public void send(){
MessageCreator messageCreator = new MessageCreator(){
public Message createMessage(Session session){
TextMessage message = null;
try {
message=session.createTextMessage("hello,I'm activeMQ");
} catch (JMSException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return message;
}
};
this.jmsTemplate.send(this.destination, messageCreator);
}
}
接收消息类,实现MessageListener接口,并实现onMessage方法;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Service;
@Service
public class GetMessage implements MessageListener{
public void onMessage(Message arg0) {
TextMessage message = (TextMessage) arg0;
try {
System.out.println(message.getText());
} catch (JMSException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
以上为全部代码,在需要发送消息的地方调用SendMessage类中的send方法就会在控制台上看到输入”Hello,I'am activeMQ“;说明发送消息成功,自动接收消息也成功了;
以上只是简单的配置应用,欢迎各位大虾指点不足。谢谢!