ActiveMQ Quick Start

Source: Internet
Author: User
Tags gettext stomp log4j

ACTIVEMQ version: 5.9.1

JDK version: 1.6_45

One, unzip the installation package, and assign permissions

[Hadoop@fedora1 ~]$ tar-xzf apache-activemq-5.9.1-bin.tar.gz 
[hadoop@fedora1 ~]$ chmod-r 775 apache-activemq-5.9.1

two. Modify the Activemq startup file

[Hadoop@fedora1 ~]$ cd apache-activemq-5.9.1/bin
[Hadoop@fedora1 bin]$ VI activemq

Search Java, add a java_home variable (if the JAVA_HOME environment variable is set, it is not required)

# Location of the Java installation
# Specify the location of your Java installation using Java_home, or specify the
  # path to the ' Java ' binary using Javacmd
# (set Javacmd to "Auto" for automatic detection)
java_home= "/home/ha Doop/jdk1.6.0_45 "
javacmd=" Auto "

You can also modify memory parameters:

# Set JVM Memory configuration
If [-Z ' $ACTIVEMQ _opts_memory]; then
    activemq_opts_memory= "-xms1g-xmx1g" 
  fi

Third, modify the configuration of the Activemq

1,broker Configuration:

[Hadoop@fedora1 bin]$ VI. /conf/activemq.xml

Broker Policy configuration:

<destinationPolicy>
	<policyMap>
		<policyEntries>
			<policyentry topic= ">" Producerflowcontrol= "true" >
			<!--If a consumer consumes messages at a slower rate, this can have an impact on non-persistent themes--
			<!-- Because messages accumulate heavily in the broker's memory, producer-flow-control,-->
			<!--will cause all producers to slow down the message, even if some consumer messages are very fast----
			<!--Fast consumers will also be slowing down their consumer messages-
			<!--to do this by adding the following policy controls--
			<!-- Broker holds up to 1000 messages for this topic, if the number of messages exceeds-           -
			<!--old messages are discarded-                                                       -
				< pendingmessagelimitstrategy>
					<constantpendingmessagelimitstrategy limit= "" "/>
				</ pendingmessagelimitstrategy>
			</policyEntry>
		</policyEntries>
	</policyMap>
</destinationPolicy>

Producer Flow Control (Producer-flow-control) configuration:

If the memory or hard disk space that the broker occupies reaches the configuration value, the broker blocks the Send () method of the message producer until some messages are consumed, and the broker can continue to receive new messages and hold new messages using the memory or hard disk space consumed by the consumed message

<systemUsage>
	<!--broker has not been able to use space will likely cause the message producer's send () method to block infinitely--
	<!--an alternative is to use the following configuration, when send ( ) method will fail and throw a-
	<!--javax.jms.ResourceAllocationException exception-                          -
	<!--< Systemusage sendfailifnospace= "true" >
	-<!--a better solution is as follows, the client waits 3000 milliseconds first and then tries
	again- <!--If the broker still does not have enough space available, throw an exception--
	<systemusage sendfailifnospaceaftertimeout= "" ">
		<!--non-persistent messages max memory size-
		<memoryUsage>
			<memoryusage percentofjvmheap= "/>"
		</memoryUsage>
		<!--persistent messages up to hard disk size-
		<storeUsage>
			<storeusage limit= " />
		</storeUsage>
		<!--temporary messages up to hard drive size-
		<tempUsage>
			<tempusage limit= "GB"/>
	  	</tempUsage>
	 </systemUsage>
</systemUsage>

Remove the non-essential communication protocol (the client and broker, broker and broker use the Protocol for communication), leaving only the TCP protocol (especially note that 61616 is the broker's listening port):

<transportConnectors>
	<!--DOS protection, limit concurrent connections to $ and frame size to 100MB--> ;
	<transportconnector name= "tcp" uri= "tcp://0.0.0.0:61616
		?maximumconnections=1000& wireformat.maxframesize=104857600 "/>
	<!--
	<transportconnector name=" AMQP "uri=" amqp:// 0.0.0.0:5672
		? maximumconnections=1000&wireformat.maxframesize=104857600 "/>
	< Transportconnector name= "Stomp" uri= "stomp://0.0.0.0:61613
		?maximumconnections=1000& wireformat.maxframesize=104857600 "/>
	<transportconnector name=" Mqtt "uri=" mqtt://0.0.0.0:1883
		? maximumconnections=1000&wireformat.maxframesize=104857600 "/>
	<transportconnector name=" ws "Uri=" ws://0.0.0.0:61614
		maximumconnections=1000&wireformat.maxframesize=104857600 "/>
-- </transportConnectors>

2,web Service configuration:

$ACTIVEMQ _home/conf/activemq.xml file was last introduced in Jetty.xml file:

<import resource= "Jetty.xml"/>

A servlet engine is built into the ACTIVEMQ (see $activemq_home/conf/jetty.xml, role permissions, validation rules, and so on in this file, not detailed here), to provide web monitoring services, the default port number is 8161:

<bean id= "Jettyport" class= "Org.apache.activemq.web.WebConsolePort" init-method= "Start" >
	<!--the Default port number for the Web console--
	<property name= "Port" value= "8161"/>
</bean>

The Web service needs to be logged in before it can be used, and the account information is stored in the $activemq_home/conf/jetty-realm.properties file:

<bean id= "Securityloginservice" class= "Org.eclipse.jetty.security.HashLoginService" >
	<property name= "Name" value= "Activemqrealm"/>
	<property name= "config" value= "${activemq.conf}/jetty-realm.properties"/ >
</bean>

$ACTIVEMQ _home/conf/jetty-realm.properties account number, account password and account role information are as follows:

# defines users that can access the Web (console, demo, etc.)
# Username:password [, rolename ...]
Admin:admin, admin
user:user, user

3, log configuration:

[Hadoop@fedora1 bin]$ VI. /conf/log4j.properties

The ACTIVEMQ log file storage path is as follows:

Log4j.appender.logfile.file=${activemq.base}/data/activemq.log ...
log4j.appender.logfile.layout.conversionpattern=%d | %-5p | %m | %c | %t%n

Four, start Activemq

[Hadoop@fedora1 bin]$ nohup./activemq Start &
[Hadoop@fedora1 bin]$ cat nohup.out 
info:using default configuration
(you can configure options in one of these F Ile:/ETC/DEFAULT/ACTIVEMQ/HOME/FEDORA1/.ACTIVEMQRC)

info:invoke The following command to create a configuration fi Le
./ACTIVEMQ Setup [/ETC/DEFAULT/ACTIVEMQ |/home/fedora1/.activemqrc]

info:using java '/home/hadoop/ Jdk1.6.0_45/bin/java '
info:starting-inspect logfiles specified in logging.properties and log4j.properties to get de Tails
Info:pidfile created: '/home/hadoop/apache-activemq-5.9.1/data/activemq-fedora1.pid ' (PID ' 14196 ')

by Ps-ef | The grep activemq command can see that the ACTIVEMQ process number is 14196

viewing log files

[Hadoop@fedora1 bin]$ Cat. /data/activemq.log

The log has the following information stating that ACTIVEMQ started successfully:

2014-07-22 15:33:03,268 | INFO  
| Apache ActiveMQ 5.9.1 (localhost, id:fedora1-50989-1406032419556-0:1) started 
| Org.apache.activemq.broker.BrokerService | Main

You can also see a lot of other important information:

2014-07-22 15:33:03,267 | INFO  
| Listening for connections at:tcp://fedora1:61616?maximumconnections=1000
&wireformat.maxframesize= 104857600 | 
org.apache.activemq.transport.TransportServerThreadSupport | main
2014-07-22 15:33:03,802 | INFO  
| ActiveMQ webconsole available at http://localhost:8161/ 
| org.apache.activemq.web.WebConsoleStarter | main
[Hadoop@fedora1 bin]$ netstat-an|grep 61616
tcp        0      0::: 61616                    :::*                        LISTEN      
[ Hadoop@fedora1 bin]$ netstat-an|grep 8161
tcp        0      0::: 8161                     :::*                        

Activemq start, you can view its status through the Web service, the account password is admin/admin:

Five, simple test

Message producers:

Import javax.jms.Connection;
Import javax.jms.Destination;
Import javax.jms.JMSException;
Import Javax.jms.MessageProducer;
Import javax.jms.Session;

Import Javax.jms.TextMessage;

Import Org.apache.activemq.ActiveMQConnectionFactory;
    public class Messagesender {private static String URL = "tcp://localhost:61616";

    private static String queue_name = "Test_queue";
        public static void Main (string[] args) {Activemqconnectionfactory factory = new Activemqconnectionfactory (URL);
        Connection conn = null;
        Session sess = null;
            try {conn = factory.createconnection ();
            Conn.start ();

            Sess = Conn.createsession (false, Session.auto_acknowledge);
            Destination dest = Sess.createqueue (queue_name);

            MessageProducer producer = Sess.createproducer (dest);
            TextMessage msg = Sess.createtextmessage ("Just a test!");
        Producer.send (msg); } catch (JMSException e) {E. Printstacktrace ();
                } finally {if (sess! = null) try {sess.close ();
                } catch (JMSException e) {e.printstacktrace ();
                } if (conn! = null) try {conn.close ();
                } catch (JMSException e) {e.printstacktrace ();
 }
        }
    }
}

Message consumers, there are two ways to achieve this:

1,listener

Import javax.jms.*;

Import Org.apache.activemq.ActiveMQConnectionFactory;
    public class Imessagelistener implements MessageListener {private static String URL = "tcp://localhost:61616";

    private static String queue_name = "Test_queue";
                public void OnMessage (Message msg) {if (null! = MSG && msg instanceof textmessage) {try {
            System.out.println ("Message:" + ((textmessage) msg). GetText ());
            } catch (JMSException e) {e.printstacktrace (); }}} public static void Main (string[] args) {Activemqconnectionfactory factory = new Activemqcon
        Nectionfactory (URL);
        Connection conn = null;
        Session sess = null;
            try {conn = factory.createconnection ();
            Conn.start ();

            Sess = Conn.createsession (false, Session.auto_acknowledge);
            Destination dest = Sess.createqueue (queue_name); Messageconsumer consumer = Sess.createconsumer (dest);
        Consumer.setmessagelistener (New Imessagelistener ());
        } catch (JMSException e) {e.printstacktrace ();
                }/*finally {///connection closed without consumer if (sess! = null) try {sess.close ();
                } catch (JMSException e) {e.printstacktrace ();
                } if (conn! = null) try {conn.close ();
                } catch (JMSException e) {e.printstacktrace ();
 }
        }*/
    }
}

2,receiver

Import javax.jms.*;

Import Org.apache.activemq.ActiveMQConnectionFactory;
    public class Imessagereceiver {private static String URL = "tcp://localhost:61616";

    private static String queue_name = "Test_queue";
        public static void Main (string[] args) {Activemqconnectionfactory factory = new Activemqconnectionfactory (URL);
        Connection conn = null;
        Session sess = null;
            try {conn = factory.createconnection ();
            Conn.start ();

            Sess = Conn.createsession (false, Session.auto_acknowledge);
            Destination dest = Sess.createqueue (queue_name);

            Messageconsumer consumer = Sess.createconsumer (dest);
                while (true) {Message message = Consumer.receive (); if (null! = message && message instanceof TextMessage) System.out.println ("message:" + ((Text
            Message). GetText ()); }} catch (JMSException e) {e.Printstacktrace ();
                } finally {if (sess! = null) try {sess.close ();
                } catch (JMSException e) {e.printstacktrace ();
                } if (conn! = null) try {conn.close ();
                } catch (JMSException e) {e.printstacktrace ();
 }
        }
    }
}

The results of the operation are as follows:

Message:just a test!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.