1, in the case of life [production problems] Why use MQ

Why use MQ

After the micro-service architecture, we are chained call the general process of writing program time, in order to complete a whole this function will split it into multiple functions (or sub-modules) such as module A calls Module B, Module B calls Module C The module C calling module D. But large-scale distributed applications, RPC interaction between system complexity, a function to be called back hundreds of interfaces is not impossible, the transition from stand-alone micro-architecture to a distributed services architecture, this architecture has no problem with it? Have
    The wind above problem, when you set up the system can be clearly grams to goal
1, to be decoupled system, when a new module in, minimal changes to the code can be done;   can be decoupled
2, the setup process buffer pool, allowing back-end systems to consume according to their own handling capacity, will not be washed away; capable of clipping
3, carding can rely on the strength of non-critical operating asynchronous call links and improve overall system throughput; asynchronously

3. What is MQ

3.1, the definition of

More message-oriented middleware (message-oriented middleware0) MOM can solve the problem.
It refers to the use of the message passing mechanism efficient and reliable data exchange platform-independent, and for distributed system integration based data communication.
Transfer and message queuing model is provided by providing a message in a distributed application environment decoupling, elastically stretchable, redundant storage, flow clipping, asynchronous communication, data synchronization
The general process
The sender of the message to the message server, message server messages stored in a number of the queue / topic, at the right time, the message server will forward the message to the recipient.
In this process, sending and receiving is asynchronous, that is sent without waiting for the sender and the recipient's life cycle is not necessarily related
Publish pub / sub subscription mode and to be complete many communication, allowing a plurality of message recipients [micro channel subscription number is this]

 

 

3.2 Features

3.2.1, asynchronous processing mode

Message sender can send a message without waiting for a response. Message sender to send the message to a virtual channel (topic or queue) on;
The message recipient or subscribe to monitor the channel. Perhaps the most complex piece of information forwarded to one or more message recipients, these recipients have no need to respond to the message sender. The entire process is asynchronous.
Case:
In other words, when a communication of this system and another system, if the system A wants to send a message to the system B, to deal with it, but do not focus on system A system B in the end how to deal with or there is no deal, so a system to send a message to MQ, then regardless of the "life and death" of the message, and then the system B MQ consumption from the inside out to process. As for how to deal with, whether processed, when processing, are unrelated matter system B, system A.

 

 Such a communication mode, the so-called "asynchronous" communications mode, for system A, as long as the message to the MQ, and the system B will be asynchronous to the processing, the system A is not "synchronized" to wait for the system B processed. What this benefit is it? Decoupling

Decoupling 3.2.2, the application system

  The sender and receiver do not have to understand each other, just make sure the message
  The sender and receiver need not be online at the same time

3.2.3, the reality of business

 

 4. What is the ActiveMQ

     Apache ActiveMQ is produced, most popular, strong ability to open source message bus. ActiveMQ is a fully supported JMS1.1 and J2EE 1.4 specification JMS Provider realize, despite the JMS specification has been introduced a long time ago, but in the middle of today's JMS J2EE application still plays a special status.
main feature:
1. multiple languages ​​and write a client agreement. Language: Java, C, C ++, C #, Ruby, Perl, Python, PHP. Application Protocol: OpenWire, Stomp REST, WS Notification, XMPP, AMQP
2. JMS1.1 and fully supports J2EE 1.4 specification (persistent, XA messages, transactions)
3. support for Spring, ActiveMQ can be easily built using Spring to go inside the system, but also supports the characteristics of Spring2.0
4. Adoption of the common J2EE server (such as Geronimo, JBoss 4, GlassFish, WebLogic) test, which by configuring JCA 1.5 resourceadaptors, allowing ActiveMQ can be automatically deployed on any compliant server business J2EE1.4
The support for multiple transport protocols: in-VM, TCP, SSL, NIO, UDP, JGroups, JXTA
6. Support provides high-speed message via JDBC persistence and journal
7. guarantee from the design of high-performance clustering, client - server, point to point
8. Support Ajax
9. Support and Axis (Apache Extensible Interaction System that is scalable Apache on .Axis interactive system that is essentially a SOAP engine that provides a server-side, client and gateway SOAP basic framework of operation) integration
10. You can easily get to call the embedded JMS provider, to test
11. Support Cluster
 

1. Download

 

 

2, installation

1, the configuration jdk environment variable [Linux] will not look back
2, mq upload the archive to Linux
 
3, to extract usr / local / ActiveMQ
 
mkdir /usr/local/ActiveMQ
the tar - zxvf Apache - ActiveMQ - . 5.15 10 - bin. the tar. GZ - C / usr / local / the ActiveMQ / 

. 5, user name and password configured [default admin / admin]
Vim the conf / Users. Properties

ADMIN = ADMIN


. 4, start and stop restart
./bin/activemq start
2
./bin/activemq stop
3
. / Bin / ActiveMQ restart


5, visit

 

5, Port Description

ActiveMQ JMS service is using port 61616 offers
Use 8161 to provide management console service
 

1, JMS messaging mode

In point at or queuing model, a release message producer to a particular queue, a consumer reads messages from the queue. Here, the producer knows the consumer's queue, and send messages directly to the consumer's queue. This model is summarized as follows: Only one consumer will get the message. Producer does not need to be running during consumption of the receiver of the message, the recipient does not need to be running at the same time sending a message. Every message successfully processed by the recipient to sign. 
Publisher / subscriber model supports publishing messages to a particular message topic. 0 or more subscribers may be interested in receiving messages from a particular message topic. In this model, publishers and subscribers who do not know each other. This mode is like an anonymous bulletin board. This model is summarized as follows: Multiple consumers can get the message time-dependent between publishers and subscribers. Publishers need to create a subscription (subscription), so that customers can purchase a subscription.
Subscribers must maintain a continuous active to receive messages, unless subscribers to establish a durable subscription. In that case, issued at the subscriber connection message will not re-publish when the subscriber reconnects.

2, JMS application programming interface

 

 

1, ConnectionFactory interface (connector factory)

the user to create a connection to a managed object JMS provider. JMS client interface access is possible by connecting the portable, so that when the underlying changes implemented,
the code does not need to be modified. Administrators configure the connection factory in the JNDI name space, so, JMS clients to be able to find them. Depending on the type of message, the user uses the queue connection factory or topic connection factory.

2, Connection interface (connector)
is connected represents a communication link between the application and the messaging server. After obtaining a connection factory, you can create a connection provided by the JMS. Depending on the type of connection, allowing the user to create a session connection, and to transmit and receive queues relating to the destination.

3, Destination Interface (target)
target is a package of the managed object identifier message destination, the message refers to a target site and the received release message or a queue or topic. JMS administrator creates these objects, and users find them via JNDI.
And the same connection factory, the administrator can create two types of goals, themes queue-point model, as well as the publisher / subscriber model

4, MessageConsumer Interface (news consumers)

    A session object created by, for receiving the transmitted message to the destination. Consumers can (blocking mode), or asynchronous (non-blocking) receive queue and topic type of synchronization message.
   
    5, MessageProducer interface (message producer)
   Object created by a session for sending a message to the target. Users can create a sender of a goal, you can create a generic sender, specify the destination when sending messages.
   6, Message Interface (message)
   
    The object is transferred between consumers and producers, that is from one application to another record application. A message has three main parts:
     
     Message header (must): to contain message for identifying and setting route seek operation.
     
    A set of message properties (optional): Contains additional properties to support compatibility with other providers and users. You can create custom fields and filters (message selector).
    
     A message body (optional): allows users to create five types of messages (text messages, mapping message, the message byte stream object message and message).
    
     Message interface is very flexible and provides many ways to customize the content of the message.
 
      7, Session Interface (session)
   It represents a single-threaded context too, for sending and receiving messages. Since the session is single-threaded, so the message is continuously available. That is a message transmitted in the order of a reception. For good conversation is that it supports transactions, if the user support transaction support, the session context will have to save a group of messages until the transaction is committed only to send these messages. Before committing the transaction, the user can use the rollback cancel these messages. It allows users to create a session to send a message generated by the message, create a message consumer to receive messages.
 

1. Create a project depend join maven

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.activemq</groupId>
    <artifactId>activemq</artifactId>
    <version>1.0-SNAPSHOT</version>

    <!--activemq需要的jar包  不是使用最新版本的。有BUG -->
    <dependencies>

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

        <!--下面是log4等通用配置 -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.25</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.2</version>
        </dependency>

    </dependencies>

</project>

  

2, the producer

Step 1: Create ConnectionFactory objects, you need to specify the server ip and port number.
Step 2: Create a Connection object using ConnectionFactory object.
Step 3: Enable connection, call the Connection object's start method.
Step Four: Create a Session object using the Connection object.
Step 5: Create a Destination objects (topic, queue) using the Session object, create a Queue object here.
Step Six: Create a Producer object using the Session object.
Step Seven: Create a Message object, creating a TextMessage object.
Eighth step: sending a message using Producer object.
Step 9: Close the resource.
 
com.activemq.demo Package; 

Import org.apache.activemq.ActiveMQConnectionFactory;

Import the javax.jms *;.

/ **
. * the Created by Administrator ON 2019-10-26
* /
public class ActiveMQ {

Private static String QUEUE = Final " Queue ";
Private static String the URL of Final =" tcp: //47.110.76.75: 61616 ";
public static void main (String [] args) throws Exception {
// Step 1: create ActiveMQConnectionFactory objects, you need to specify the server IP and IP port number .//brokerURL server to get the port number.
ConnectionFactory = new new ActiveMQConnectionFactory ActiveMQConnectionFactory (the URL of);
// Step 2: Use connectionFactory create a connection object
Connection connection = connectionFactory.createConnection ();
// third step: open access, call connection objects start method was
connection.start ();
// Step Four: Create a session object using the Connection object to
the Session session = connection.createSession (false, Session.AUTO_ACKNOWLEDGE);
// step Five: create the Destination objects (topic, queue) using the Session object, create a Queue object here. // parameters: the name of the queue too.
= Session.createQueue Queue Queue (QUEUE);
// Step Six: Create a Producer object using the session object
MessageProducer Producer = session.createProducer (Queue);
// Step Seven: Create a new new ActiveMQTextMessage = the Message ();
TextMessage textMessage session.createTextMessage = ( "Hello ActiveMQ, the this IS My First Test");
// eighth step:
producer.send (textMessage);

// a ninth step
producer.close ();
Session.close ();
Connection.close ();
System.out.println ( "producer sends success message to the MQ!");


}
}


 
         
After the completion of the production can see the news generated

 

 

3, consumers

Consumers There are two methods of consumption:

1, synchronized consumption. Consumers receive by calling the method to display a message extracted from the destination, receive method can block until a message arrives.

2, asynchronous consumption. Customers can register a message listener for the consumer, was to define the actions to be taken when a message arrives.

MessageListener implement interface, message processing logic MessageListener give () method.

 

4, synchronization is generally not recommended [consumer]

Step 1: Create a connection factory

Step 2: Create a connection

The third step: open connection

Step Four: Create Session

Step 5: Create destination

Step Six: Create consumer

Step Seven: receiving a message

Step eight: Turn off resources

com.activemq.demo Package; 

Import org.apache.activemq.ActiveMQConnectionFactory;

Import the javax.jms *;.

/ **
. * the Created by Administrator ON 2019-10-26
* /
public class ActiveMQ {

Private static String QUEUE = Final " Queue ";
Private static String the URL of Final =" tcp: //47.110.76.75: 61616 ";
public static void main (String [] args) throws Exception {
// Step 1: create ActiveMQConnectionFactory objects, you need to specify the server IP and IP port number .//brokerURL server to get the port number.
ConnectionFactory = new new ActiveMQConnectionFactory ActiveMQConnectionFactory (the URL of);
// Step 2: Use connectionFactory create a connection object
Connection connection = connectionFactory.createConnection ();
// third step: open access, call connection objects start method was
connection.start ();
// Step Four: Create a session object using the Connection object to
the Session session = connection.createSession (false, Session.AUTO_ACKNOWLEDGE);
// step Five: create the Destination objects (topic, queue) using the Session object, create a Queue object here. // parameters: the name of the queue too.
= Session.createQueue Queue Queue (QUEUE);
// Step Six: Create a Producer object using the session object
MessageProducer Producer = session.createProducer (Queue);
// Step Seven: Create a new new ActiveMQTextMessage = the Message ();
TextMessage textMessage session.createTextMessage = ( "Hello ActiveMQ, the this IS My First Test");
// eighth step:
producer.send (textMessage);

// a ninth step
producer.close ();
Session.close ();
Connection.close ();
System.out.println ( "producer sends success message to the MQ!");


}
}

 

4.1, receive Method Description

receive () has been blocked

receive (1000) 10 does not receive the message class seconds to give

 

5, asynchronous consumers [Recommended]

Step 1: Create a ConnectionFactory object.

Step Two: Get a Connection object from the ConnectionFactory object.

Step 3: Enable connection, call the Connection object's start method.

Step Four: Create a Session object using the Connection object.

Step 5: Create a Destination object using the Session object. And transmitting end consistent queue, and the same name of the queue.

Step Six: Create a Consumer object using the Session object.

Step Seven: receiving a message.

Step eight: Print a message.

Step 9: Close the resource.

 

 

 

 

 

 

Guess you like

Origin www.cnblogs.com/jacksonxiao/p/11745675.html
Recommended