Spring 整合 ActiveMQ-01-入门
2018年9月20日大约 2 分钟
Spring ActiveMQ 整合实战
基础知识
实战代码
环境准备
启动 activeMQ,本次测试使用 docker。
项目结构
├── pom.xml
└── src
├── main
│ ├── java
│ │ └── com
│ │ └── github
│ │ └── houbb
│ │ └── jms
│ │ └── learn
│ │ └── activemq
│ │ └── spring
│ │ ├── listener
│ │ │ └── ConsunerMessageListener.java
│ │ └── service
│ │ ├── ProducerService.java
│ │ └── impl
│ │ └── ProducerServiceImpl.java
│ └── resources
│ └── application-mq.xml
└── test
└── java
└── com
└── github
└── houbb
└── jms
└── learn
└── activemq
└── spring
└── ActiveMQTest.java
maven jar 引入
- pom.xml
4.2.5.RELEASE
junit
junit
4.12
test
org.springframework
spring-context
${spring.version}
org.springframework
spring-jms
${spring.version}
org.springframework
spring-test
${spring.version}
javax.annotation
jsr250-api
1.0
org.apache.activemq
activemq-core
5.7.0
文件配置
- application-mq.xml
queue
实现代码
- ProducerService 接口及其实现
public interface ProducerService {
/**
* 发送消息
* @param msg 消息
*/
void sendMsg(final String msg);
}
import com.github.houbb.jms.learn.activemq.spring.service.ProducerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
@Service
public class ProducerServiceImpl implements ProducerService {
@Autowired
private JmsTemplate jmsTemplate;
@Autowired
private Destination destination;
@Override
public void sendMsg(String msg) {
System.out.println("生产者发了一个消息:" + msg);
jmsTemplate.send(destination, new MessageCreator() {
@Override
public Message createMessage(Session session) throws JMSException {
return session.createTextMessage(msg);
}
});
}
}
- ConsunerMessageListener 消息监听器
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;
public class ConsunerMessageListener implements MessageListener {
@Override
public void onMessage(Message message) {
//这里我们知道生产者发送的就是一个纯文本消息,所以这里可以直接进行强制转换
TextMessage textMsg = (TextMessage) message;
System.out.println("接收到一个纯文本消息。");
try {
System.out.println("消息内容是:" + textMsg.getText());
} catch (JMSException e) {
e.printStackTrace();
}
}
}
测试
- ActiveMQTest.java
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:application-mq.xml"})
public class ActiveMQTest {
@Autowired
private ProducerService producerService;
@Test
public void sendTest() {
producerService.sendMsg("hello spring activeMQ!");
}
}
- 测试日志
生产者发了一个消息:hello spring activeMQ!
接收到一个纯文本消息。
消息内容是:hello spring activeMQ!
源码地址
参考资料
贡献者
binbin.hou