ActiveMQ(1)- 简介和入门程序

一、ActiveMQ简介

ActiveMQ是Apache发布的一款功能强大的消息中间件,是基于JMS 1.1和J2EE 1.4规范,目前使用十分广泛。

ActiveMQ的主要特点如下:

  • 实现了JMS规范
  • 支持多种语言Java,C++,C#,Ruby,Perl,Python,PHP
  • 提供了AMQP v1.0规范和MQTT v3.1规范的支持;
  • 支持许多消息队列的高级特性,如消息组、虚拟目的地、组合目的地等;
  • 可支持JDBC的高行能、快速消息持久化;
  • 方便与Spring进行整合

二、环境搭建(Linux)

  1. 下载
    在ActiveMQ官网可以下载到安装包,目前最新的稳定版本是 ActiveMQ 5.15.9版本
  2. 安装
    解压安装包
tar -zxvf apache-activemq-5.15.9-bin.tar.gz
  1. 运行
cd apache-activemq-5.15.9/bin
./activemq start

ActiveMQ成功启动,默认监听61616端口。可以使用netstat命令查看端口监听状态。

netstat -nltp | grep 61616

ActiveMQ 提供了一个管理界面,可以通过浏览器访问用于监控队列状态和消息进行操控。
管理台的端口为8161:http:localhost:8161/admin
密码和用户名都为admin

  1. 关闭
    可通过activemq脚本精选关闭
activemq stop
activemq state   ---查看状态

三、SpringBoot整合ActiveMQ的入门案例

SpringBoot提供了对JMS的支持。因为ActiveMQ实现了JMS规范,因此可以使用SpringBoot快速整合ActiveMQ。

  1. 在pom文件内添加activemq的依赖
<!-- 引入activeMQ依赖 -->
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-activemq</artifactId>
</dependency>
  1. 添加ActiveMQ的配置
#ActiveMQ的配置
spring:
	activemq:
		broker-url: 'tcp://localost:61616' #配置Broker URL,默认为tcp//localost:61616  localhost为activemq所在的主机ip地址
		in-memory: true
		pool: 
		 enabled: false
  1. 消息生产者
    Spring提供了JmsTemplate模板,可以方便对JMS进行操作
/**
 * @author 林摇
 * @date 2019/3/8 10:19
 * @description ActiveMQ消息生产者
 */
@Service
public class MessageProduer {
	//可以注入JMSMessagingTemplate模板
	@Autowired
	private JmsMessagingTemplate jmsMessagingTemplate;
	/**
	 * 发送消息
	 * @param destination 要发送的队列
	 * @param payload 待发送的消息
	 */
	public void sendMessage(Destination destination,String payload) {
		jmsMessagingTemplate.convertAndSend(destination, payload);
	}
}
  1. 消息消费者
    Spring提供了@JMSListener注解,可以申明式注册消息监听器
/**
 * @author 林摇
 * @date 2019/3/8 10:20
 * @description ActiveMQ的消息消费者
 */
@Service
public class MessageConsumer {

	/**
	 * 监听指定队列的消息
	 * @param message 消息
	 */
	//JmsListener监听指定队列
	@JmsListener(destination="my-queue")
	public void receiveMessage(String message) {
		System.out.println("接收了消息:"+message);
	}
}
  1. 测试
@SpringBootTest
@RunWith(SpringRunner.class)
public class TestActiveMQ {
	@Autowired
	private MessageProduer producer;
	@Test
	public void testSendMessage() {
		Destination destination=new ActiveMQQueue("my-queue");
		for (int i = 0; i < 100; i++) {
			producer.sendMessage(destination, i+"");
		}
	}
}

输出结果为

接收了消息:0
接收了消息:1
接收了消息:2
接收了消息:3
接收了消息:4
接收了消息:5
接收了消息:6
接收了消息:7
接收了消息:8
接收了消息:9
接收了消息:10
接收了消息:11
接收了消息:12
接收了消息:13
····

猜你喜欢

转载自blog.csdn.net/weixin_44715918/article/details/88927661