【ActiveMQ】ActiveMQ在Spring Boot下使用
1.activemq服务端安装
下载apache-activemq-5.15.3:
wget http://mirror.bit.edu.cn/apache//activemq/5.15.3/apache-activemq-5.15.3-bin.tar.gz
解压
tar -zxvf apache-activemq-5.15.3
启动
./activemq start
连接管理界面
(需关闭linux防火墙:systemctl stop firewalld.service
)
http://ip:8161(ip为安装activemq的ip,如为本机则为localhost)
1.activemq依赖
//核心
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-activemq</artifactId>
</dependency>
//连接池
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-pool</artifactId>
</dependency>
2.连接配置
#连接地址tcp://ip:port,默认为61616端口
spring.activemq.broker-url=tcp://192.168.179.132:61616
#用户名和密码,默认为admin
spring.activemq.user=admin
spring.activemq.password=admin
测试
//生产者
@Component
public class Producer {
private final JmsTemplate jmsTemplate;
@Autowired
public Producer(JmsTemplate jmsTemplate) {
this.jmsTemplate = jmsTemplate;
}
/**
* 发送消息
* @param destination
* 发送到的队列
* @param message
* 待发送的消息
*/
void sendMessage(Destination destination, final String message) {
jmsTemplate.convertAndSend(destination, message);
}
}
//消费者
@Component
public class Consumer {
@JmsListener(destination = "queue")
public void receiveQueue(String text) {
System.out.println("收到消息"+text);
}
}
//测试类
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
public class ActivemqTest {
@Autowired
private Producer producer;
@Test
public void contextLoads() throws InterruptedException {
Destination destination = new ActiveMQQueue("queue");
int times = 10;
for (int i = 0; i < times; i++) {
producer.sendMessage(destination, "hello"+i);
}
}
}
结果:
收到消息hello0
收到消息hello1
收到消息hello2
收到消息hello3
收到消息hello4
收到消息hello5
收到消息hello6
收到消息hello7
收到消息hello8
收到消息hello9
网络上志同道合,我们一起学习网络安全,一起进步,QQ群:694839022