Message middleware: ActiveMQ

ActiveMQ (Message Queue) comes from apache, an open source message bus.

Fully supports JMS 1.1 and J2EE 1.4 specification JMS Provider implementation, very fast

Official website: http://activemq.apache.org/ 

 

1. Features

  • Write clients in multiple languages ​​and protocols. Languages: Java, C, C++, C#, Ruby, Perl, Python, PHP. Application Protocol: OpenWire, Stomp REST, WS Notification, XMPP, AMQP
  • Full support for JMS1.1 and J2EE 1.4 specifications (persistence, XA messages, transactions)
  • For the support of Spring, ActiveMQ can be easily embedded into the system using Spring, and also supports the features of Spring 2.0
  • Passed the test of common J2EE servers (such as Geronimo, JBoss 4, GlassFish, WebLogic), and through the configuration of JCA 1.5 resource adaptors, ActiveMQ can be automatically deployed to any compatible J2EE 1.4 commercial server.
  • Supports multiple transport protocols: in-VM, TCP, SSL, NIO, UDP, JGroups, JXTA
  • Supports high-speed message persistence via JDBC and journal
  • High-performance clustering, client-server, peer-to-peer, guaranteed by design
  • Ajax support
  • Support integration with Axis
  • It is easy to call the embedded JMS provider for testing

Second, when to use

  • Integration between multiple projects 
  • Reduce the coupling degree of modules between systems, decoupling 
  • Front-end and back-end isolation of the system

three, start

   Windows: Double-click the activemq.bat script in the bin directory

   linux: ./activemq start    ./activemq stop

 

Four, test

      ActiveMQ default connection port is 61616,

     You can test whether ActiveMQ starts successfully by viewing the information of this port. netstat -an|find "61616"

 

Five, monitoring

   When ActiveMQ is started by default, the built-in jetty server is started, providing an admin application for monitoring ActiveMQ. 

 

   admin:http://127.0.0.1:8161/admin/             user/pwd: admin/admin

 

Six, the way of communication

  1, publish-subscribe: publish-subscribe mode, one-to-many relationship.

   2, P2P

       In the p2p scenario, the two parties communicating with each other communicate through a queue-like way.

       The difference from ub-sub is that a topic has one sender and multiple receivers.

         In p2p, a queue has only one sender and one receiver.

   3, request-response

      Both parties need to be able to send messages to each other

  Remarks: Reference:  http://shmilyaw-hotmail-com.iteye.com/blog/1897635

                    https://www.cnblogs.com/zhuxiaojie/p/5564187.html

 

Seven, security configuration

activemq/conf/jetty.xml:

   <pre name="code" class="html"> <bean id="securityConstraint" class="org.eclipse.jetty.util.security.Constraint">
        <property name="name" value="BASIC" />
        <property name="roles" value="admin" />
         <!-- Change this to true, of course, the higher version has been changed to true -->
        <property name="authenticate" value="true" />
  </bean>

 Find activemq/conf/activemq.xml and open it

<plugins>
             <simpleAuthenticationPlugin>
                 <users>
                     <authenticationUser username="${activemq.username}" password="${activemq.password}" groups="users,admins"/>
                 </users>
             </simpleAuthenticationPlugin>
</plugins>

 Then the account password is configured in the activemq/conf/credentials.properties file

#account
activemq.username=admin
#password
activemq.password=123456
guest.password=password

 

eight example

process:

     1. Obtain the JMS connection factory. Construct the factory by providing the connection information for the specific environment.

     2. Use factory to construct JMS connection

     3. Start the connection

     4. Create a JMS session through the connection.

     5. Specify the JMS destination.

     6. Create a JMS producer or create a JMS message and provide a destination.

     7. Create a JMS consumer or register a JMS message listener.

     8. Send and receive JMS messages.

     9. Close all JMS resources, including connection, session, producer, consumer, etc.

 

public class Producter {

    //Default username for ActiveMq
    private static final String USERNAME = ActiveMQConnection.DEFAULT_USER;
    //Default login password for ActiveMq
    private static final String PASSWORD = ActiveMQConnection.DEFAULT_PASSWORD;
    //Link address of ActiveMQ
    private static final String BROKEN_URL = ActiveMQConnection.DEFAULT_BROKER_URL;

    AtomicInteger count = new AtomicInteger(0);
    // link factory
    ConnectionFactory connectionFactory;
    // link object
    Connection connection;
    // transaction management
    Session session;
    ThreadLocal<MessageProducer> threadLocal = new ThreadLocal<>();

    public void init(){
        try {
            //create a link factory
            connectionFactory = new ActiveMQConnectionFactory(USERNAME,PASSWORD,BROKEN_URL);
            //create a link from the factory
            connection  = connectionFactory.createConnection();
            // open the link
            connection.start();
            //Create a transaction (here, the level of the transaction can be set by parameters)
            session = connection.createSession(true,Session.SESSION_TRANSACTED);
        } catch (JMSException e) {
            e.printStackTrace ();
        }
    }

    public void sendMessage(String disname){
        try {
            //create a message queue
            Queue queue = session.createQueue(disname);
            // message producer
            MessageProducer messageProducer = null;
            if(threadLocal.get()!=null){
                messageProducer = threadLocal.get();
            }else{
                messageProducer = session.createProducer(queue);
                threadLocal.set(messageProducer);
            }
           while(true){
                Thread.sleep(1000);
                int num = count.getAndIncrement();
                //create a message
                TextMessage msg = session.createTextMessage(Thread.currentThread().getName()+
                        "productor: I'm a handsome guy, I'm producing stuff now!,count:"+num);
                System.out.println(Thread.currentThread().getName()+
                        "productor: I'm a handsome guy, I'm producing stuff now!,count:"+num);
                //send messages
                messageProducer.send(msg);
                // commit the transaction
                session.commit();
            }
        } catch (JMSException e) {
            e.printStackTrace ();
        } catch (InterruptedException e) {
            e.printStackTrace ();
        }
    }
}

 

public class Comsumer {

    private static final String USERNAME = ActiveMQConnection.DEFAULT_USER;

    private static final String PASSWORD = ActiveMQConnection.DEFAULT_PASSWORD;

    private static final String BROKEN_URL = ActiveMQConnection.DEFAULT_BROKER_URL;

    ConnectionFactory connectionFactory;

    Connection connection;

    Session session;

    ThreadLocal<MessageConsumer> threadLocal = new ThreadLocal<>();
    AtomicInteger count = new AtomicInteger();

    public void init(){
        try {
            connectionFactory = new ActiveMQConnectionFactory(USERNAME,PASSWORD,BROKEN_URL);
            connection  = connectionFactory.createConnection();
            connection.start();
            session = connection.createSession(false,Session.AUTO_ACKNOWLEDGE);
        } catch (JMSException e) {
            e.printStackTrace ();
        }
    }


    public void getMessage(String disname){
        try {
            Queue queue = session.createQueue(disname);
            MessageConsumer consumer = null;

            if(threadLocal.get()!=null){
                consumer = threadLocal.get();
            }else{
                consumer = session.createConsumer(queue);
                threadLocal.set(consumer);
            }
            while(true){
                Thread.sleep(1000);
                TextMessage msg = (TextMessage) consumer.receive();
                if(msg!=null) {
                    msg.acknowledge();
                    System.out.println(Thread.currentThread().getName()+": Consumer: I am a consumer, I am consuming Msg"+msg.getText()+"--->"+count.getAndIncrement()) ;
                }else {
                    break;
                }
            }
        } catch (JMSException e) {
            e.printStackTrace ();
        } catch (InterruptedException e) {
            e.printStackTrace ();
        }
    }
}

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326101269&siteId=291194637