Java Message Middleware---Basic article __java

Source: Internet
Author: User
Tags gettext sessions

Learning MU web Java Message Middleware take notes 1. Overview

Middleware
Non-underlying operating system software, non-business application software, is not directly to the end user, can not directly bring value to customers of the software collectively referred to as middleware.
Message middleware
Control focuses on the sending and receiving of data and integrates distributed systems with efficient and reliable asynchronous messaging mechanisms.
Advantages
① decoupling ② Asynchronous ③ horizontal extension ④ safe and reliable ⑤ order guarantees (e.g. Kafka)
Jms
The Java Messaging Service, or JMS, is a Java platform for message-oriented middleware APIs for sending messages between two applications, or distributed systems, for asynchronous communication
What is AMQP
AMQP (Advanced Message Queuing Protocol) is a standard protocol for the application layer that provides unified messaging services, and the client and message middleware based on this protocol can deliver messages that are not limited by the different products of client/middleware, different development languages, etc.
Common Message Middleware
ActiveMQ (supports multiple languages, implements jms1.1,j2ee1.4 specification), RABBITMQ (supports more languages, based on AMQP specification), Kafka (high throughput, distributed, partitioned, O (1) disk order provides message persistence)

JMS message Mode
Queue mode
Clients include producers and consumers
Messages in queues can only be consumed by one consumer
Consumers can consume messages in the queue at any time
Theme Mode
Clients include publishers and Subscribers
Messages in the subject are consumed by all subscribers
Messages sent to a topic before consumers can consume subscriptions
JMS Coded interface
ConnectionFactory is used to create a connection factory connecting to message middleware
Connection represents the communication link between the application and the messaging server
Destination refers to the place where messages are published and received, including queues or topics
The session represents a single-threaded context for sending and receiving messages
Messageconsumer is created by the session to receive messages sent to the destination
MessageProducer is created by the session to send messages to the destination
Messages are objects sent between consumers and producers, message headers, a set of message attributes, a message body
Process
2. Install ACTIVEMQ

Official website: http://activemq.apache.org/
The first type of startup
Enter Bin, Activemq.bat start
Enter Browser http://127.0.0.1:8161
User name password defaults to admin
The second type starts with a service
Installservice.bat Run as Administrator
There are activemq in the service
Linux
Unzip the compressed package
Enter bin input activemq start, start completion 3.JMS demo

Create MAVEN Project
Add dependencies

   <dependency>
      <groupId>org.apache.activemq</groupId>
      <artifactid>activemq-all </artifactId>
      <version>5.9.0</version>
    </dependency>

Create a queue mode producer Appproducer

Package com.jms.queue;
Import javax.jms.Connection;
Import Javax.jms.ConnectionFactory;
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 Appproducer {public static final String url = ' tcp://localhost:61616 ';

    public static final String queuename = "Queue-test"; public static void Main (string[] args) throws JMSException {//1. Create a connection factory connectionfactory

        y = new activemqconnectionfactory (URL);

        2. Create Connection Connection Connection = Connectionfactory.createconnection ();

        3. Start connection Connection.start ();

        4. Create session first parameter: whether to be handled in a transaction, the second argument. Answer mode Sessions session = Connection.createsession (false, Session.auto_acknowledge);

        5. Create a target destination Destination = Session.createqueue (queuename); 6 Create a producer MesSageproducer producer = Session.createproducer (destination); for (int i = 0; i < i++) {//7. Infrastructure news TextMessage TextMessage = Session.createtextmessage ("
            Test: "+i);
            Producer.send (TextMessage);
        SYSTEM.OUT.PRINTLN ("Send Message:" +textmessage.gettext ());
    //9 Closes the connection connection.close ();
 }
}

Run project, open ACTIVEMQ management tool

100 messages, no consumer consumption, connection closed
consumer Appconsumer

Package com.jms.queue;
Import javax.jms.Connection;
Import Javax.jms.ConnectionFactory;
Import javax.jms.Destination;
Import javax.jms.JMSException;
Import Javax.jms.Message;
Import Javax.jms.MessageConsumer;
Import Javax.jms.MessageListener;
Import javax.jms.Session;

Import Javax.jms.TextMessage;

Import Org.apache.activemq.ActiveMQConnectionFactory;
    public class Appconsumer {public static final String url = ' tcp://localhost:61616 ';

    public static final String queuename = "Queue-test"; public static void Main (string[] args) throws JMSException {//1. Create a connection factory connectionfactory

        y = new activemqconnectionfactory (URL);

        2. Create Connection Connection Connection = Connectionfactory.createconnection ();

        3. Start connection Connection.start ();

        4. Create session first parameter: whether to be handled in a transaction, the second argument. Answer mode Sessions session = Connection.createsession (false, Session.auto_acknowledge); 5. Create a target destination destination = sesSion.createqueue (QueueName);

        6 Create a consumer messageconsumer consumber = Session.createconsumer (destination); 7 Create a listener Consumber.setmessagelistener (new MessageListener () {public void OnMessage
                ) {TextMessage TextMessage = (textmessage) message;
                try {System.out.println ("Receive Message:" +textmessage.gettext ());
                catch (JMSException e) {e.printstacktrace ();

        }

            }
        });
    8 Off the connection message is asynchronous, the program exit is off, and the//connection.close can not be closed here ();
 }
}

When starting 2 consumers, restart the producer, the result is 2 consumer average consumption

Create a Theme mode publisher Appproducer

Package com.jms.topic;
Import javax.jms.Connection;
Import Javax.jms.ConnectionFactory;
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 Appproducer {public static final String url = ' tcp://localhost:61616 ';

    public static final String topicname = "Topic-test"; public static void Main (string[] args) throws JMSException {//1. Create a connection factory connectionfactory

        y = new activemqconnectionfactory (URL);

        2. Create Connection Connection Connection = Connectionfactory.createconnection ();

        3. Start connection Connection.start ();

        4. Create session first parameter: whether to be handled in a transaction, the second argument. Answer mode Sessions session = Connection.createsession (false, Session.auto_acknowledge);

        5. Create a target destination Destination = Session.createtopic (topicname); 6 Create a producer MesSageproducer producer = Session.createproducer (destination); for (int i = 0; i < i++) {//7. Infrastructure news TextMessage TextMessage = Session.createtextmessage ("
            Test: "+i);
            Producer.send (TextMessage);
        SYSTEM.OUT.PRINTLN ("Send Message:" +textmessage.gettext ());
    //9 Closes the connection connection.close (); }
}


The direct run subscriber cannot receive the message because the publisher first runs the

Subscriber Appconsumer

Package com.jms.topic;
Import javax.jms.Connection;
Import Javax.jms.ConnectionFactory;
Import javax.jms.Destination;
Import javax.jms.JMSException;
Import Javax.jms.Message;
Import Javax.jms.MessageConsumer;
Import Javax.jms.MessageListener;
Import javax.jms.Session;

Import Javax.jms.TextMessage;

Import Org.apache.activemq.ActiveMQConnectionFactory;
    public class Appconsumer {public static final String url = ' tcp://localhost:61616 ';

    public static final String topicname = "Topic-test"; public static void Main (string[] args) throws JMSException {//1. Create a connection factory connectionfactory

        y = new activemqconnectionfactory (URL);

        2. Create Connection Connection Connection = Connectionfactory.createconnection ();

        3. Start connection Connection.start ();

        4. Create session first parameter: whether to be handled in a transaction, the second argument. Answer mode Sessions session = Connection.createsession (false, Session.auto_acknowledge); 5. Create a target destination destination = sesSion.createtopic (topicname);

        6 Create a consumer messageconsumer consumber = Session.createconsumer (destination); 7 Create a listener Consumber.setmessagelistener (new MessageListener () {public void OnMessage
                ) {TextMessage TextMessage = (textmessage) message;
                try {System.out.println ("Receive Message:" +textmessage.gettext ());
                catch (JMSException e) {e.printstacktrace ();

        }

            }
        });
    The 8 off Connection message is asynchronous, in the program exit is closed//connection.close ();
 }
}

Start two subscribers, restart the publisher, and two subscribers can receive message 4 from the publisher . Using spring integrated JMS link ACTIVEMQ

ConnectionFactory the factory used to manage connections
Jmstemplate the template class used to send and receive messages
Messagelisterner Message Listener

ConnectionFactory is the connection pool that spring provides for us
Two kinds of connection pools singleconnectionfactory and Cachingconnectionfactory
Singleconnectionfactory is a request for JMS, which returns only one connection
Cachingconnectionfactory implements all the features of the Singleconnectionfactory and also provides a cache

Jmstemplate Spring provides, thread-safe, you can use the jmstemplate to manipulate JMS

Messagelisterner implement OnMessage method, receive message parameters

Add dependencies

    <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jms<
        /artifactid> <version>${spring.version}</version> </dependency> <dependency>
        <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupid>or G.springframework</groupid> <artifactId>spring-context</artifactId> &LT;VERSION&GT;${SPR ing.version}</version> </dependency> <dependency> <groupId>org.springframework< /groupid> <artifactId>spring-web</artifactId> <version>${spring.version}</version&
    Gt </dependency> <dependency> <groupId>org.springframework</groupId> <artifactid& Gt;spring-test</artifactid> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.apache.activemq</groupId> <artifactId>activemq-core</artifactId> < version>5.7.0</version> <exclusions> <exclusion> <artifactid>spring-c
      Ontext</artifactid> <groupId>org.springframework</groupId> </exclusion> </exclusions> </dependency>

Notice here that ORG.APACHE.ACTIVEMQ also relies on spring-context, so we're going to get him out of here.

Producer Creation Interface Producerservice

Package com.spring.producer;

Public interface Producerservice {

    void SendMessage (String message);

}

Implementation class

Package Com.spring.producer.impl;
Import Javax.annotation.Resource;
Import javax.jms.Destination;
Import javax.jms.JMSException;
Import Javax.jms.Message;
Import javax.jms.Session;

Import Javax.jms.TextMessage;
Import org.springframework.beans.factory.annotation.Autowired;
Import Org.springframework.jms.core.JmsTemplate;
Import Org.springframework.jms.core.MessageCreator;

Import Org.springframework.stereotype.Service;
Import Com.spring.producer.ProducerService; 
    @Service public class Producerserviceimpl implements Producerservice {@Autowired private jmstemplate jmstemplate;

    @Resource (name= "queuedestination")//Because multiple destinations may be configured, Resource name is used to differentiate destination destination; public void SendMessage (final String message) {//Jmstemplate send messages using the Jmstemplate.send (destination,new Messa
                Gecreator () {///Create messages Public message CreateMessage throws JMSException { TextMessage TextMessage = session.createtextmessAge (message);
            return textmessage;
        }
        });
    SYSTEM.OUT.PRINTLN ("Send message:" +message);
 }

}

Configuration

<?xml version= "1.0" encoding= "UTF-8"? ><beans xmlns= "Http://www.springframework.org/schema/beans" xmlns: context= "Http://www.springframework.org/schema/context" xmlns:mvc= "Http://www.springframework.org/schema/mvc" Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xsi:schemalocation= "Http://www.springframework.org/sche Ma/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd http://www.springframework. Org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd http://www.spring Framework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd "> <context:ann otation-config></context:annotation-config> <context:component-scan base-package= "com.spring.*"/&
        Gt <!--ACTIVEMQ offers connectionfactory--> <bean id= "targetconnectionfactory" class= " Org.apache.activemq.ActiveMQConnectionFactory "> &Lt;property name= "Brokerurl" value= "tcp://localhost:61616" ></property> </bean> <!--SPRING-JMS offers
    Connection pool--> <bean id= "ConnectionFactory" class= "Org.springframework.jms.connection.SingleConnectionFactory" > <property name= "Targetconnectionfactory" ref= "Targetconnectionfactory" ></property> </bean> & lt;!  --a queue destination, point to point--> <bean id= "queuedestination" class= "Org.apache.activemq.command.ActiveMQQueue" > <!-- Specify queue name--> <constructor-arg value= "Springqueue" ></constructor-arg> </bean> <bean I D= "Jmstemplate" class= "org.springframework.jms.core.JmsTemplate" > <property name= "ConnectionFactory" ConnectionFactory "></property> </bean> <!--<bean id=" Producerserviceimpl "class=" com.spring. Producer.impl.ProducerServiceImpl "></bean>--> </beans>

Start class

Package com.spring.producer;

Import Org.springframework.context.ApplicationContext;
Import Org.springframework.context.support.AbstractApplicationContext;
Import Org.springframework.context.support.ClassPathXmlApplicationContext;

public class Appproducer {public
    static void Main (string[] args) {
        ApplicationContext context = new Classpathxmla Pplicationcontext ("Producer.xml");
        Producerservice service = Context.getbean (producerservice.class);
        for (int i=0;i<100;i++) {
            service.sendmessage ("Test" +i);
        }
        The Resource
        ((abstractapplicationcontext) context) is automatically cleaned up. Close ();
    }

We can extract the public places.

<import resource= "Common.xml"/>

Create consumer
Configuration

<?xml version= "1.0" encoding= "UTF-8"? ><beans xmlns= "http://" Www.springframework.org/schema/beans "xmlns:context=" Http://www.springframework.org/schema/context "xmlns:mvc=" Http://www.springframework.org/schema/mvc "xmlns:xsi=" Http://www.w3.org/2001/XMLSchema-instance "xsi: schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/be Ans/spring-beans-4.3.xsd 
Related Article

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.