Данное приложение, содержащее все необходимые для работы с БД Oracle библиотеки, может быть установлено в систему Debian виде пакета hydra-activemq
из репозитория deb.hydra-billing.com
. Подключение данного репозитория может быть выполнено сотрудниками компании Латера в рамках услуги техподдержки.
Предварительные требования
Для работы последней версии ActiveMQ необходимо наличие на сервере Oracle Java версии 8. Установка может быть выполнена следующим образом:
root@server:~# echo "deb http://ppa.launchpad.net/webupd8team/java/ubuntu trusty main" | tee /etc/apt/sources.list.d/webupd8team-java.list && \ echo "deb-src http://ppa.launchpad.net/webupd8team/java/ubuntu trusty main" | tee -a /etc/apt/sources.list.d/webupd8team-java.list && \ apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys EEA14886 && \ echo oracle-java8-installer shared/accepted-oracle-license-v1-1 select true | sudo /usr/bin/debconf-set-selections && \ aptitude update && \ aptitude install oracle-java8-installer
root@server:~# java -version java version "1.8.0_121" Java(TM) SE Runtime Environment (build 1.8.0_121-b13) Java HotSpot(TM) 64-Bit Server VM (build 25.121-b13, mixed mode)
Настройка ActiveMQ
Конфигурация экземпляра брокера, необходимая для работы провижининга состоит из нескольких частей, описанных ниже.
Основные параметры экземпляра брокера
<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 http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd"> <!-- Allows us to use system properties as variables in this configuration file --> <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" /> <!-- The <broker> element is used to configure the ActiveMQ broker. --> <broker xmlns="http://activemq.apache.org/schema/core" brokerName="provisioning" 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> <!-- 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://127.0.0.1:61616?maximumConnections=1000&wireFormat.maxFrameSize=104857600"/> <transportConnector name="stomp" uri="stomp://127.0.0.1:61613?transport.hbGracePeriodMultiplier=1.5"/> </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> <camelContext xmlns="http://camel.apache.org/schema/spring" id="camel"> <route> <from uri="oracleTopic:topic:AIS_NET.HP_COMMANDS_1?clientId=ActiveMQ&durableSubscriptionName=HP"/> <to uri="activemq:queue:hydra_commands_1"/> </route> <route> <from uri="activemq:queue:hydra_command_results_1"/> <to uri="oracleTopic:topic:AIS_NET.HP_COM_RES_1?clientId=ActiveMQ&durableSubscriptionName=HP"/> </route> <route> <from uri="oracleTopic:topic:AIS_NET.HP_PROFILES_1?clientId=ActiveMQ&durableSubscriptionName=HP"/> <to uri="activemq:queue:hydra_profiles_1"/> </route> <route> <from uri="oracleTopic:topic:AIS_NET.HP_EQUIPMENT_BINDS_1?clientId=ActiveMQ&durableSubscriptionName=HP"/> <to uri="activemq:queue:hydra_equipment_binds_1"/> </route> </camelContext> <bean id="activeMQConfig" class="org.apache.activemq.camel.component.ActiveMQConfiguration"> <property name="cacheLevelName" value="CACHE_CONSUMER" /> <property name="concurrentConsumers" value="1" /> </bean> <bean id="connectionFactoryOracleAQTopic" class="oracle.jms.AQjmsFactory" factory-method="getQueueConnectionFactory"> <constructor-arg index="0"> <value>jdbc:oracle:thin:@//127.0.0.1:1521/hydra</value> </constructor-arg> <constructor-arg index="1" type="java.util.Properties"> <value></value> </constructor-arg> </bean> <bean id="oracleTopicCredentials" class="org.springframework.jms.connection.UserCredentialsConnectionFactoryAdapter"> <property name="targetConnectionFactory"> <ref bean="connectionFactoryOracleAQTopic"/> </property> <property name="username"> <value>AIS_PROVISIONING</value> </property> <property name="password"> <value>read_manual</value> </property> </bean> <bean id="oracleTopic" class="org.apache.camel.component.jms.JmsComponent"> <property name="connectionFactory" ref="oracleTopicCredentials"/> </bean> <!-- Enable web consoles, REST and Ajax APIs and demos Take a look at ${ACTIVEMQ_BASE}/conf/jetty.xml for more details --> <import resource="jetty.xml"/> </beans>
В данном примере конфигурации настроено следующее:
- Брокер слушает порт
127.0.0.1:61616
для взаимодействия с агентом HEX по протоколу OpenWire; - Брокер слушает порт
127.0.0.1:61613
для взаимодействия с агентом HARD по протоколу STOMP; - Сообщения с командами для выполнения агентом HEX брокер извлекает из очереди
HP_COMMANDS_1
схемыAIS_NET
БД Oracle и помещает их в свою очередьhydra_commands_1
; - Сообщения с результатами выполнения команд от агента HEX брокер извлекает из своей очереди
hydra_command_results_1
и помещает их в очередьHP_COM_RES_1
схемыAIS_NET
БД Oracle; - Сообщения с профилями оборудования для агента HARD брокер извлекает из очереди
HP_PROFILES_1
схемыAIS_NET
БД Oracle и помещает их в свою очередьhydra_profiles_1
; - Сообщения с привязками оборудования для агента HARD брокер извлекает из очереди
HP_EQUIPMENT_BINDS_1
схемыAIS_NET
БД Oracle и помещает их в свою очередьhydra_equipment_binds_1
; - БД Oracle называется
hydra
и доступна на порту127.0.0.1:1521
; - Для работы с БД Oracle используется пользователь базы данных
AIS_PROVISIONING
c паролемread_manual
.
Данные для доступа к очередям
## --------------------------------------------------------------------------- ## Licensed to the Apache Software Foundation (ASF) under one or more ## contributor license agreements. See the NOTICE file distributed with ## this work for additional information regarding copyright ownership. ## The ASF licenses this file to You under the Apache License, Version 2.0 ## (the "License"); you may not use this file except in compliance with ## the License. You may obtain a copy of the License at ## ## http://www.apache.org/licenses/LICENSE-2.0 ## ## Unless required by applicable law or agreed to in writing, software ## distributed under the License is distributed on an "AS IS" BASIS, ## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ## See the License for the specific language governing permissions and ## limitations under the License. ## --------------------------------------------------------------------------- # Defines credentials that will be used by components (like web console) to access the broker activemq.username=system activemq.password=manager
В данном примере для работы с брокером настроен пользователь с логином system
и паролем manager
.
Параметры ведения логов
## --------------------------------------------------------------------------- ## Licensed to the Apache Software Foundation (ASF) under one or more ## contributor license agreements. See the NOTICE file distributed with ## this work for additional information regarding copyright ownership. ## The ASF licenses this file to You under the Apache License, Version 2.0 ## (the "License"); you may not use this file except in compliance with ## the License. You may obtain a copy of the License at ## ## http://www.apache.org/licenses/LICENSE-2.0 ## ## Unless required by applicable law or agreed to in writing, software ## distributed under the License is distributed on an "AS IS" BASIS, ## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ## See the License for the specific language governing permissions and ## limitations under the License. ## --------------------------------------------------------------------------- # # This file controls most of the logging in ActiveMQ which is mainly based around # the commons logging API. # log4j.rootLogger=INFO, console, logfile log4j.logger.org.apache.activemq.spring=WARN log4j.logger.org.apache.activemq.web.handler=WARN log4j.logger.org.springframework=WARN log4j.logger.org.apache.xbean=WARN log4j.logger.org.apache.camel=INFO log4j.logger.org.eclipse.jetty=WARN # When debugging or reporting problems to the ActiveMQ team, # comment out the above lines and uncomment the next. #log4j.rootLogger=DEBUG, logfile, console # Or for more fine grained debug logging uncomment one of these #log4j.logger.org.apache.activemq=DEBUG #log4j.logger.org.apache.camel=DEBUG # Console appender log4j.appender.console=org.apache.log4j.ConsoleAppender log4j.appender.console.layout=org.apache.log4j.PatternLayout log4j.appender.console.layout.ConversionPattern=%5p | %m%n log4j.appender.console.threshold=INFO # File appender log4j.appender.logfile=org.apache.log4j.RollingFileAppender log4j.appender.logfile.file=${activemq.base}/data/provisioning-activemq.log log4j.appender.logfile.maxFileSize=1024KB log4j.appender.logfile.maxBackupIndex=5 log4j.appender.logfile.append=true log4j.appender.logfile.layout=org.apache.log4j.PatternLayout log4j.appender.logfile.layout.ConversionPattern=%d | %-5p | %m | %c | %t%n # use some of the following patterns to see MDC logging data # # %X{activemq.broker} # %X{activemq.connector} # %X{activemq.destination} # # e.g. # # log4j.appender.logfile.layout.ConversionPattern=%d | %-20.20X{activemq.connector} | %-5p | %m | %c | %t%n ########### # Audit log ########### log4j.additivity.org.apache.activemq.audit=false log4j.logger.org.apache.activemq.audit=INFO, audit log4j.appender.audit=org.apache.log4j.RollingFileAppender log4j.appender.audit.file=${activemq.base}/data/provisioning-audit.log log4j.appender.audit.maxFileSize=1024KB log4j.appender.audit.maxBackupIndex=5 log4j.appender.audit.append=true log4j.appender.audit.layout=org.apache.log4j.PatternLayout log4j.appender.audit.layout.ConversionPattern=%-5p | %m | %t%n
В данном примере настроена запись логов работы брокера в файл provisioning-activemq.log
, расположенный в директории с данными очередей. При установке ActiveMQ из пакета hydra-activemq
данный файл будет доступен как /var/log/hydra/activemq/provisioning-activemq.log
.
Параметры веб-интерфейса контроля состояния очередей
Для версии ActiveMQ < 5.14
Согласно данному примеру конфигурации веб-интерфейс контроля состояния очередей будет доступен по адресу http://127.0.0.1:8161/
.
Для версии ActiveMQ >= 5.14
Данные для доступа к веб-интерфейсу контроля состояния очередей
## --------------------------------------------------------------------------- ## Licensed to the Apache Software Foundation (ASF) under one or more ## contributor license agreements. See the NOTICE file distributed with ## this work for additional information regarding copyright ownership. ## The ASF licenses this file to You under the Apache License, Version 2.0 ## (the "License"); you may not use this file except in compliance with ## the License. You may obtain a copy of the License at ## ## http://www.apache.org/licenses/LICENSE-2.0 ## ## Unless required by applicable law or agreed to in writing, software ## distributed under the License is distributed on an "AS IS" BASIS, ## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ## See the License for the specific language governing permissions and ## limitations under the License. ## --------------------------------------------------------------------------- # Defines users that can access the web (console, demo, etc.) # username: password [,rolename ...] admin: admin, admin
В данном примере для доступа к веб-интерфейсу контроля состояния очередей создан пользователь с логином admin
, паролем admin
и ролью admin
.
Включение и запуск
После настройки экземпляра необходимо его активировать, создав в /etc/hydra/activemq/instances-enabled
указывающую на него символьную ссылку и перезапустить ActiveMQ инициализационным скриптом.
root@server:~# cd /etc/hydra/activemq/instances-enabled && \ ln -s ../instances-available/provisioning
root@server:~# /etc/init.d/hydra-activemq restart
user@server:~$ ls -lR /etc/hydra/activemq/instances-available/ && \ ls -l /etc/hydra/activemq/instances-enabled/ && \ sudo /etc/init.d/hydra-activemq status
Для доступа к административному веб-интерфейсу брокера можно использовать консольный браузер links
:
user@server:~$ links http://admin:admin@127.0.0.1:8161/admin/