1、加入依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-activemq</artifactId> </dependency>
如果使用pool的话, 就需要在pom中加入以下依赖:
<dependency> <groupId>org.apache.activemq</groupId> <artifactId>activemq-pool</artifactId> <version>5.14.5</version> </dependency>
2、yml文件
spring: activemq: broker-url: tcp://192.168.0.1:61616 user: admin password: admin pool: # 使用flase,此处改为true报错,不清楚什么原因 enabled: false max-connections: 10 queueName: publish.queue topicName: publish.topic
3、创建生产者producer
@Service("producer") public class Producer { @Autowired private JmsMessagingTemplate jmsTemplate; public void sendMsg(String destinationName ,String message){ System.out.println("------------ 发送消息"+ message); Destination destination = new ActiveMQQueue(destinationName); jmsTemplate.convertAndSend(destination,message); } }
4、创建消费者consumer
@Component public class Consumer { @JmsListener(destination = "test.queue") public void listen(String text){ System.out.println("<<<========= 收到消息" + text); } }
注意: @JmsListener是一个可重复的注解,在java7及以下版本jdk中,可以使用@JmsListeners代替它。
5、测试类
*/ @RunWith(SpringRunner.class) @SpringBootTest public class JMSProducerTest { @Autowired private Producer producer; @Test public void sendMsg() throws Exception { for (int i = 0; i < 10 ; i++) { producer.sendMsg("test.queue","Queue Message"+i); } } }