ActiveMQ(三):安全机制、消息持久化

一、安全机制

1.1、修改activemq.xml文件

<broker></broker>标签下配置<plugins>标签。

<beans
  xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
  http://activemq.apache.org/schema/core http://activemq.apache.org/schema/core/activemq-core.xsd">

    <!-- Allows us to use system properties as variables in this configuration file -->
    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <value>file:${activemq.conf}/credentials.properties</value>
        </property>
    </bean>

   <!-- Allows accessing the server log -->
    <bean id="logQuery" class="io.fabric8.insight.log.log4j.Log4jLogQuery"
          lazy-init="false" scope="singleton"
          init-method="start" destroy-method="stop">
    </bean>

    <!--
        The <broker> element is used to configure the ActiveMQ broker.
    -->
    <broker xmlns="http://activemq.apache.org/schema/core" brokerName="localhost" dataDirectory="${activemq.data}">

        <destinationPolicy>
            <policyMap>
              <policyEntries>
                <policyEntry topic=">" >
                    <!-- The constantPendingMessageLimitStrategy is used to prevent
                         slow topic consumers to block producers and affect other consumers
                         by limiting the number of messages that are retained
                         For more information, see:

                         http://activemq.apache.org/slow-consumer-handling.html

                    -->
                  <pendingMessageLimitStrategy>
                    <constantPendingMessageLimitStrategy limit="1000"/>
                  </pendingMessageLimitStrategy>
                </policyEntry>
              </policyEntries>
            </policyMap>
        </destinationPolicy>


        <!--
            The managementContext is used to configure how ActiveMQ is exposed in
            JMX. By default, ActiveMQ uses the MBean server that is started by
            the JVM. For more information, see:

            http://activemq.apache.org/jmx.html
        -->
        <managementContext>
            <managementContext createConnector="false"/>
        </managementContext>

        <!--
            Configure message persistence for the broker. The default persistence
            mechanism is the KahaDB store (identified by the kahaDB tag).
            For more information, see:

            http://activemq.apache.org/persistence.html
        -->
        <persistenceAdapter>
            <kahaDB directory="${activemq.data}/kahadb"/>
        </persistenceAdapter>


          <!--
            The systemUsage controls the maximum amount of space the broker will
            use before disabling caching and/or slowing down producers. For more information, see:
            http://activemq.apache.org/producer-flow-control.html
          -->
          <systemUsage>
            <systemUsage>
                <memoryUsage>
                    <memoryUsage percentOfJvmHeap="70" />
                </memoryUsage>
                <storeUsage>
                    <storeUsage limit="100 gb"/>
                </storeUsage>
                <tempUsage>
                    <tempUsage limit="50 gb"/>
                </tempUsage>
            </systemUsage>
        </systemUsage>

        <!--
            The transport connectors expose ActiveMQ over a given protocol to
            clients and other brokers. For more information, see:

            http://activemq.apache.org/configuring-transports.html
        -->
        <transportConnectors>
            <!-- DOS protection, limit concurrent connections to 1000 and frame size to 100MB -->
            <transportConnector name="openwire" uri="tcp://0.0.0.0:61616?maximumConnections=1000&amp;wireFormat.maxFrameSize=104857600"/>
            <transportConnector name="amqp" uri="amqp://0.0.0.0:5672?maximumConnections=1000&amp;wireFormat.maxFrameSize=104857600"/>
            <transportConnector name="stomp" uri="stomp://0.0.0.0:61613?maximumConnections=1000&amp;wireFormat.maxFrameSize=104857600"/>
            <transportConnector name="mqtt" uri="mqtt://0.0.0.0:1883?maximumConnections=1000&amp;wireFormat.maxFrameSize=104857600"/>
            <transportConnector name="ws" uri="ws://0.0.0.0:61614?maximumConnections=1000&amp;wireFormat.maxFrameSize=104857600"/>
        </transportConnectors>

        <!-- destroy the spring context on shutdown to stop jetty -->
        <shutdownHooks>
            <bean xmlns="http://www.springframework.org/schema/beans" class="org.apache.activemq.hooks.SpringContextHook" />
        </shutdownHooks>
		
		<!-- 在<broker>标签下配置<plugins>标签 -->
		<plugins>
			<simpleAuthenticationPlugin>
				<users>
					<authenticationUser username="admin" password="admin" groups="admins,publishers,consumers"/>
				</users>
			</simpleAuthenticationPlugin>
		</plugins>

    </broker>

    <!--
        Enable web consoles, REST and Ajax APIs and demos
        The web consoles requires by default login, you can disable this in the jetty.xml file

        Take a look at ${ACTIVEMQ_HOME}/conf/jetty.xml for more details
    -->
    <import resource="jetty.xml"/>

</beans>

1.2、配置用户名密码

在没有配置<broker>用户名和密码的情况下,创建连接只需要将用户名指定为ActiveMQConnectionFactory.DEFAULT_USER,将密码指定为ActiveMQConnectionFactory.DEFAULT_PASSWORD即可。

// 1、创建连接工厂
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(
        ActiveMQConnectionFactory.DEFAULT_USER,
        ActiveMQConnectionFactory.DEFAULT_PASSWORD,
        "tcp://localhost:61616"
);

查看源码可以发现,其实这俩个值都是null,所以此时相当于没有配置用户名与密码。

public static final String DEFAULT_USER = null;
public static final String DEFAULT_PASSWORD = null;

此时如果使用用户名密码都为null进行连接,会抛出异常。

Exception in thread "main" javax.jms.JMSSecurityException: User name [null] or password is invalid.
	at org.apache.activemq.util.JMSExceptionSupport.create(JMSExceptionSupport.java:52)
	at org.apache.activemq.ActiveMQConnection.syncSendPacket(ActiveMQConnection.java:1403)
	at org.apache.activemq.ActiveMQConnection.ensureConnectionInfoSent(ActiveMQConnection.java:1486)
	at org.apache.activemq.ActiveMQConnection.createSession(ActiveMQConnection.java:329)

将代码修改为如下代码,即可成功连接。

// 1、创建连接工厂
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(
        "admin",
        "admin",
        "tcp://localhost:61616"
);

二、消息持久化

2.1、KahaDB存储

KahaDB是默认的持久化策略,所有消息顺序添加到一个日志文件中,同时另外有一个索引文件指向这些日志的存储地址。KahaDB存储是一个专门针对消息持久化的解决方案。

2.1.1、文件说明

在data/kahadb目录下,会生成四个文件,来完成消息的持久化:

  1. db.data:消息的索引文件,本质上是B树,使用B树作为索引指向db-*.log文件中存储的消息。
  2. db-*.log:存储消息内容,以追加的形式顺序写入,文件大小默认阈值时32M,达到阈值会自动递增。
  3. db.redo:用于重启后的消息恢复。
  4. lock:锁,写入当前获得kahaDB读写权限的broker,用于集群环境下的读写权限的竞争。

2.1.2、特性

KahaDB的特性:

  1. 追加形式存储消息。
  2. 消息索引以B-Tree结构存储,可以快速更新。
  3. 完全支持JMS事务。
  4. 可以限制每个数据文件的大小,当db-1.log达到阈值时,会创建db-2.log进行消息的存储。

2.2、JDBC存储(Mysql8)

效率较低,一般不用于生产环境,但是便于我们查看持久化数据。

2.2.1、配置文件

<beans>标签下添加bean

<!-- 数据源 Bean -->
<bean id="mysql-source" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close">
	<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
	<property name="url" value="jdbc:mysql://localhost/activemq?relaxAutoCommit=true&amp;serverTimezone=UTC&amp;characterEncoding=utf8&amp;useUnicode=true&amp;useSSL=false"/>
	<property name="username" value="root"/>
	<property name="password" value="root"/>
	<property name="maxTotal" value="200"/>
	<property name="poolPreparedStatements" value="true"/>
</bean>

配置持久化方式为JDBC,修改<broker>标签下的persistenceAdapter为:

<persistenceAdapter>
	<!-- 会自动创建表,但是需要自己创建数据库activemq-->
    <jdbcPersistenceAdapter dataSource="#mysql-source" createTablesOnstartup="true"/>
</persistenceAdapter>

2.2.2、添加Jar包

lib目录下添加Jar包
mysql-connector-java-8.0.19.jar
commons-pool2-2.6.0.jar
JAR包下载地址

2.2.3、数据库与数据表

需要手动创建数据库create database activemq;,表会自动创建。
启动ActiveMQ后会自动创建以下三张表
在这里插入图片描述

  • activemq_msgs:消息内容,发送后会添加相应记录,消费完后会自动删除
    ID:自增主键
    CONTAINER:容器名称
    MSGID_PROD:消息发送者客户端的主键
    MSGID_SEQ:消息的序列,msgid_prod+msg_seq可以组成jms的messageid
    EXPIRATION:消息的过期时间,存储的是毫秒数
    MSG:消息体的序列化二进制数据
    PRIORITY:优先级,从0-9,数值越大优先级越高
  • activemq_acks:用于存储订阅关系。如果是持久化Topic,订阅者和服务器的订阅关系在这个表保存
    CONTAINER:消息的目的地
    SUB_DEST:集群其他系统的信息
    CLIENT_ID:订阅者客户端ID
    SUB_NAME:订阅者名称
    SELECTOR:选择器
    LAST_ACKED_ID:记录消费过的消息的id。
    PRIORITY:优先级
  • activemq_lock:锁表,用于集群环境下的读写权限的竞争。
    ID:主键
    TIME:时间
    BROKER_NAME:Broker名称
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

it00zyq

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值