Apache activemq установка linux

Version 5 Getting Started

Introduction

This document describes how to install and configure ActiveMQ for both Unix and Windows’ platforms.

Pre-Installation Requirements

Hardware:

  • 60 MB of free disk space for the ActiveMQ binary distribution.
  • 200 MB of free disk space for the ActiveMQ source or developer’s distributions.

Operating Systems:

  • Windows: Windows XP SP2, Windows 2000.
  • Unix: Ubuntu Linux, Powerdog Linux, MacOS, AIX, HP-UX, Solaris, or any Unix platform that supports Java.

Environment:

  • Java Developer Kit (JDK) 1.7.x or greater for deployment and 1.7.x (Java 7) for compiling/building.
  • The JAVA_HOME environment variable must be set to the directory where the JDK is installed, e.g., c:\Program Files\jdk.1.7.0_xx_xx .
  • Maven 3.0 or greater (required when installing source or developer’s releases).
  • JARs that will be used must be added to the classpath.

Installation Procedure for Windows

This section of the Getting Started Guide explains how to install binary and source distributions of ActiveMQ on a Windows system.

Windows Binary Installation

This procedure explains how to download and install the binary distribution on a Windows system.

  1. From a browser, navigate to activemq.apache.org/.
  2. Click the Download link in the navigation pane (the left pane).
  3. Select the latest distribution (for older releases, click the link to the archives).
    For a binary distribution, the filename will be similar to: activemq-x.x.x.zip .
  4. Extract the files from the ZIP file into a directory of your choice.
  5. Proceed to the #Starting ActiveMQ section of this document.
  6. Following start-up, go to the #Testing the Installation section of this document.

Windows Source Installation

This procedure explains how to download and install the source distribution on a Windows system.

NOTE: ActiveMQ requires Java 7 to run and to build

  1. From a browser, navigate to activemq.apache.org/.
  2. Click the Download link in the navigation pane (the left pane).
  3. Select the latest distribution (for older releases, click the link to the archives).
    For a source distribution, the filename will be similar to: activemq-x.x-src.zip .
  4. Extract ActiveMQ from the ZIP file into a directory of your choice.
  5. Build ActiveMQ using Maven 2.1 or greater and Java 1.7.

The recommended method of building ActiveMQ is the following:

where [activemq_install_dir] is the directory in which ActiveMQ was installed.

If the above build fails on some tests, type the following:

Источник

Повышаем производительность Ruby on rails приложений с помощью ActiveMQ

В своём посте хочу рассказать о возможности использования ActiveMQ в проекте написанном на фреймворке Ruby on rails.

Что такое Message Queue?

MQ – это архитектура обмена сообщениями между компонентами приложения в асинхронном режиме. Т. е. отправитель и получатель могут взаимодействовать в разное время. Состоят такие системы из producer’а (отправителя) и consumer’a (получателя) которые взаимодействуют между собой через broker.

Используя такие системы можно существенно увеличить производительность приложения, выполняя код в асинхронном режиме. Допустим у вас есть код который очень замедляет выполнение какой то части на вашем сайте, чтобы пользователь не ждал завершение работы такого кода, лучше его выполнить в асинхронном режиме. Несколько простых примеров:
— генерация thumbnails;
— сбор статистики;
— рассылка писем/сообщений;
— удаление данных с таблиц;
— индексация данных;
— импорт данных в базу.

Таких примеров может быть много, думаю, каждый может найти часть кода у себя в проекте, который можно вынести для выполнения в асинхронном режиме.

Что такое ActiveMQ?

ActiveMQ — это открытая реализация message broker системы. Преимущество данной системы это высокая производительность, открытость и возможность реализации клиентов на любых языках. ActiveMQ в данный момент поддерживает следующее протоколы:
— OpenWire (собственный бинарный протокол);
— Stomp;
— REST;
— WS Notification;
— XMPP.

Читайте также:  Nvidia quadro fx 1700 driver windows 10

Установка ActiveMQ

Описание будет идти для Linux, хотя думаю проблем с установкой на Windows не должно быть. Выполняем следующие команды:

wget apache.multihomed.net/activemq/apache-activemq/5.2.0/apache-activemq-5.2.0-bin.tar.gz
tar xvf apache-activemq-5.2.0-bin.tar.gz
sudo cp -R ./apache-activemq-5.2.0 /usr/local/apache-activemq

Установка завершена. Запускаем ActiveMQ:

Все готово к работе.

Работа с ActiveMQ на Ruby on rails

Чтобы понять, на сколько удобно выполнять код в асинхронном режиме, давайте для начала создадим код который будет долго выполняется.

rails test
cd test
script/generate controller test
script/server

Преобразуем код контроллера Test к следующему виду:

class TestController ‘Data saved’
end
end

Открываем http://0.0.0.0:3000/test/index и видим, что приходиться какое-то время ждать завершение работы кода. У меня бенчмарк показал, что данный код выполняется 10 секунд, очень много, не каждый пользователь готов ждать такое время.

Для взаимодействия с ActiveMQ я предлагаю использовать плагин ActiveMessaging, хочу отметить, что есть возможность использовать непосредственно Stomp клиент. Но в таком случае мы потеряем возможность легко и просто переключиться на другую систему MQ.

ActiveMessaging — это плагин для Ruby on rails который очень легко использовать в проекте для выполнения кода в асинхронном режиме. Поддерживает большое количество протоколов, в том числе и Stomp, т.е. мы можем его использовать для работы с ActiveMQ.

Устанавливаем его в проект:

script/plugin install activemessaging.googlecode.com/svn/trunk/plugins/activemessaging

также нам нужно установить клиент для работы с stomp протоколом:

gem install stomp

ActiveMessaging имеет два конфигурационных файлов:
— config/broker.yml — содержит настройки для подключения;
— config/messaging.rb — содержит настройки очередей.

Выполняемый код в асинхронном режиме пишется в так званных процессорах. Для генерации нашего первого процессора выполним следующую команду:

script/generate processor Test

Открываем наш процессор (/app/processors/test_proccesor.rb) и переносим сюда тестовый код:

Преобразуем код экшена index на следующее:

def index
publish :test, ‘Some test message’
render :text => ‘Message sent’
end

Здесь мы просто передаём сообщение ‘Some test message’ в destination под именем test, т. е. выполняем функцию producer’а. Если вы откроете конфигурационный файл config/messaging.rb то вы увидите под именем destination’а test очередь /queue/Test, в которую наше сообщение и будет отправлено.

Запускаем демон, который является у нас consumer’ом, т.е. он будет читать все сообщения с очереди /queue/Test и передавать их процессору TestProcessor.

Для чистоты теста удаляем наш файл в который мы писали данные:

Обновляем страницу http://0.0.0.0:3000/test/index и сразу видим, что код выполняется практически моментально, а теперь идем в tmp и видим вновь созданный файл test с данным. Также можно перейти в лог и там увидеть сообщение ‘Data saved’.

В большинстве случаев нам нужно выполнить код с какими то параметрами. Мы можем перевести хеш с параметрами в XML, JSON или Yaml и передать в виде сообщения. Я предпочитаю JSON.

Давайте попробуем передать количество записываемых строк и само сообщение, которое записывается в файл. Немного изменим экшен index:

def index
publish :test, <:count =>200000, :message => ‘Some new test message’>.to_json
render :text => ‘Message sent’
end

Изменим и метод on_message:

def on_message(message)
options = JSON.parse(message).symbolize_keys
path = File.join(RAILS_ROOT, ‘tmp’, ‘test’)
file_test = File.new(path, ‘w’)

logger.debug ‘Data saved’
end

Так как в ruby нет стандартных функций для работы с JSON, нужно установить gem:

sudo gem install json

и подключить его в TestProcessor:

Теперь прерываем работу нашего демона и запускаем заново:

script/poller stop
script/poller start

Снова обновляем страницу http://0.0.0.0:3000/test/index. Открыв файл tmp/test, мы увидим перезаписанный файл уже строками ‘Some new test message’.

В процессоре очень легко использовать модели, точно также как и в обычных экшенах. Небольшой пример для наглядности:

def on_message(message)
options = JSON.parse(message).symbolize_keys

Product.find(:all).each do |product|
product.price = options[:price]
product.save
end
end

В ActiveMQ существует утилита, в которой вы сможете смотреть статистику отосланных сообщений, список очередей и даже отослать сообщение, очень удобно использовать для отладки. Находиться она по адресу http://0.0.0.0:8161/admin/.

Надеюсь, этот пост продемонстрировал простоту и преимущество использования ActiveMQ в проекте. Всего-навсего небольшой рефакторинг в вашем проекте и приложение задышит по другому.

Источник

Getting Started

Introduction

This document describes how to install and configure ActiveMQ 5.x for both Unix and Windows’ platforms.

Document Organization

The Getting Started Guide for ActiveMQ 5.x document contains the following sections:

Pre-Installation Requirements

Hardware:

60 MB of free disk space for the ActiveMQ 5.x binary distribution.
(you need additional disk space for storing persistent messages to disk)

Читайте также:  Сжать том с установленной windows 10

300 MB of free disk space for the ActiveMQ 5.x source or developer’s distributions.

  • Windows: Windows XP SP2, Windows 2000, Windows Vista, Windows 7.
  • Unix: Ubuntu Linux, Powerdog Linux, MacOS, AIX, HP-UX, Solaris, or any Unix platform that supports Java.

Environment:

  • Java Runtime Environment (JRE)В JRE 1.8 or greater (1.7 for version “The latest stable release” -> “apache-activemq-x.x.x-bin.zip”)
  • Extract the files from the ZIP file into a directory of your choice.
  • Proceed to the #Starting ActiveMQ section of this document.
  • Following start-up, go to the #Testing the Installation section of this document.

Windows Source Installation

This procedure explains how to download and install the source distribution on a Windows system.

  1. Download the latest release
    (see Download -> “The latest stable release” -> “apache-activemq-x.x.x-source-release.zip”)
  2. Extract ActiveMQ from the ZIP file into a directory of your choice.
  3. The recommended method of building ActiveMQ is the following:

where [activemq_install_dir] is the directory in which ActiveMQ was installed.

If you prefer to use an IDE, then you can auto-generate the IDE’s project file using maven plugins:

Feel free to use any other applicable IDE. Please refer to the plugin reference for more details.

Start ActiveMQ from the target directory, for example:

NOTE: Working directories get created relative to the current directory. To create the working directories in the proper place, ActiveMQ must be launched from its home/installation directory.

If you are building ActiveMQ 4.x under Windows using Cygwin there is a path name length limitation. If the path name length is exceeded, you may see build errors. To correct this, move the ActiveMQ source directory higher in the file system tree, e.g., /cygdrive/c/d/sm.

Windows Developer’s Release

This procedure explains how to download and install the latest developer’s snapshot.

  1. Open the release archive: https://repository.apache.org/content/repositories/snapshots/org/apache/activemq/apache-activemq/
    (open one of the SNAPSHOT directories)
  2. Select the version of ActiveMQ to download (if necessary, scroll down to see the ActiveMQ snapshots).
  3. Extract the files from the ZIP file into a directory of your choice.
  4. If a binary snapshot was downloaded, proceed to the #Starting ActiveMQ section of this document.
    If a source snapshot was downloaded, perform step 6 and step 7 of the #Windows Source Installation procedure.
  5. Following start-up, proceed to the #Testing the Installation section.

Installation Procedure for Unix

Unix Binary Installation

This procedure explains how to download and install the binary distribution on a Unix system.
NOTE: There are several alternative ways to perform this type of installation.

    Download the activemq zipped tarball file to the Unix machine, using either a browser or a tool, i.e., wget, scp, ftp, etc. for example:
    (see Download -> “The latest stable release”)

Proceed to the #Starting ActiveMQ section of this document.

Using Homebrew installer on OSX

If you use OSX as your platform, you can use Homebrew package manager to easily install Apache ActiveMQ.

    After installing Homebrew package manager successfully, just run

You can expect the following output:

ActiveMQ will be installed in /usr/local/Cellar/apache-activemq/x.x.x/ directory (where x.x.x denotes the actual version being installed).

Unix Source Installation

This procedure explains how to download and install the source distribution on a Unix system. This procedure assumes the Unix machine has a browser. Please see the previous #Unix Binary Installation section for details on how to install ActiveMQ without a browser.

  1. Download the latest source release
    (see Download -> “The latest stable release” -> “activemq-parent-x.x.x-source-release.zip”)
  2. Extract the files from the ZIP file into a directory of your choice. For example:

If Maven crashes with a java.lang.OutOfMemoryError, you you need to do this first (assuming a Bourne-like shell):

If you prefer to use an IDE then you can auto-generate the IDE’s project file using maven plugins:

Feel free to use any other applicable IDE. Please refer to the plugin reference for more details.
NOTE: Working directories get created relative to the current directory. To create working directories in the proper place, ActiveMQ must be launched from its home/installation directory.

Unix Developer’s Release

This procedure explains how to download and install the latest developer’s snapshot.

  1. Open the release archive: https://repository.apache.org/content/repositories/snapshots/org/apache/activemq/apache-activemq/
    (open one of the SNAPSHOT directories)
  2. Select the version of ActiveMQ to download (you may have to scroll down to see the ActiveMQ snapshots).
    The filename will be similar to: activemq-x.x.x-tar.gz .
  3. Extract the files from the gzip file into a directory of your choice. For example:
    For a binary developer’s snapshot:

For a source developer’s snapshot:

Starting ActiveMQ

There now follows instructions on how to run the ActiveMQ Message Broker.

On Windows:

From a console window, change to the installation directory and run ActiveMQ :

where [activemq_install_dir] is the directory in which ActiveMQ was installed, e.g., c:\Program Files\ActiveMQ-5.x .
Then type:

`NOTE:** Working directories get created relative to the current directory. To create working directories in the proper place, ActiveMQ must be launched from its home/installation directory.

On Unix:

From a command shell, change to the installation directory and run ActiveMQ as a foregroud process:

From a command shell, change to the installation directory and run ActiveMQ as a daemon process:

More help

For other ways of running the broker see Here. For example you can run an embedded broker inside your JMS Connection to avoid starting a separate process.

Testing the Installation

Using the administrative interface

  • Open the administrative interface
    • URL: http://127.0.0.1:8161/admin/
    • Login: admin
    • Passwort: admin
  • Navigate to “Queues”
  • Add a queue name and click create
  • Send test message by klicking on “Send to”

Logfile and console output

If ActiveMQ is up and running without problems, the Window’s console window or the Unix command shell will display information similar to the following log line (see stdout output or “[activemq_install_dir]/data/activemq.log”):

Listen port

ActiveMQ’s default port is 61616. From another window run netstat and search for port 61616.

From a Windows console, type:

OR

From a Unix command shell, type:

Monitoring ActiveMQ

You can monitor ActiveMQ using the Web Console by pointing your browser at http://localhost:8161/admin .

From ActiveMQ 5.8 onwards the web apps is secured out of the box.
The default username and password is admin/admin. You can configure this in the conf/jetty-real.properties file.

Or you can use the JMX support to view the running state of ActiveMQ.

For more information see the file docs/WebConsole-README.txt in the distribution.

Stopping ActiveMQ

For both Windows and Unix installations, terminate ActiveMQ by typing “CTRL-C” in the console or command shell in which it is running.

If ActiveMQ was started in the background on Unix, the process can be killed, with the following:

Configuring ActiveMQ

The ActiveMQ broker should now run. You can configure the broker by specifying an Xml Configuration file as a parameter to the activemq command. An alternative is to use the Broker Configuration URI to configure things on the command line in a concise format (though the configuration options are not as extensive as if you use Java or XML code). You can also

Also see Configuring Transports to see how you can configure the various connection, transport and broker options using the connection URL in the ActiveMQConnectionFactory.

See the Initial Configuration for details of which jars you need to add to your classpath to start using ActiveMQ in your Java code

If you want to use JNDI to connect to your JMS provider then please view the JNDI Support. If you are a Spring user you should read about Spring Support

After the installation, ActiveMQ is running with a basic configuration. For details on configuring options, please see refer to the Configuration section.

Additional Resources

If you are new to using ActiveMQ, running the Web Samples or the Examples is a good next step to learn more about ActiveMQ.

The commercial providers listed on the issues page may also have additional documentation, examples, tutorials, etc… that can help you get started.

Apache, ActiveMQ, Apache ActiveMQ, the Apache feather logo, and the Apache ActiveMQ project logo are trademarks of The Apache Software Foundation. Copyright © 2021, The Apache Software Foundation. Licensed under Apache License 2.0.

Источник

Читайте также:  Huawei e352 драйвер для windows
Оцените статью