Can we use Ajax instead of JMS


ActiveMQ functions

ActiveMQ is an open source messaging middleware from Apache that is designed to provide applications with efficient, scalable, stable and secure messaging at the enterprise level. The design goal is to provide a standard, message-oriented, multilingual middleware for message communication for application integration. ActiveMQ implements JMS 1.1 and offers many additional functions such as JMX management, master-slave management, message group communication, message priority, delayed message reception, virtual recipients, message persistence, message queue monitoring, etc. Its main features are:

  1. It supports clients and protocols in multiple languages ​​including Java, C, C ++, C #, Ruby, Perl, Python, PHP, etc. The protocols include OpenWire, Stomp, AMQP, MQTT.
  2. Provides advanced features like newsgroup communication, message priority, delayed message reception, virtual recipient, message persistence, etc.
  3. Full support for JMS 1.1 and J2EE 1.4 specifications (including persistence, distributed transactional messages, transactions)
  4. ActiveMQ supports the Spring framework and can be easily embedded in Spring applications using Spring configuration files
  5. Passed general J2EE server tests such as TomEE, Geronimo, JBoss, GlassFish and WebLogic
  6. ActiveMQ offers different connection modes and different connection modes such as: B. In-VM, TCP, SSL, NIO, UDP, Multicast, JGroups and JXTA
  7. Support for fast persistence of messages using JDBC and Journal
  8. Designed for high performance clusters, client-server, point-to-point communication and other scenarios
  9. Provides a technology and language-neutral REST API interface
  10. Help Ajax invoke ActiveMQ
  11. ActiveMQ integrates easily with CXF, Axis, and other web service technologies for reliable messaging
  12. Can be used as an in-memory JMS provider and is very suitable for JMS unit tests

basic concept

Since ActiveMQ fully supports JMS 1.1, its basic concepts from the perspective of Java users are consistent with the JMS 1.1 specification.

Messaging model
  1. Point-to-point (point-to-point) model Use the queue (queue) as the message communication provider to meet the manufacturer and consumer model. A message can only be used by one consumer and the message is not used. Stay in the queue until it is consumed or expired.

  2. The publication and subscription model (pub / sub) uses the subject as a message communication medium, similar to broadcast mode. The editor publishes a message. The message is delivered in a message to all subscribers about the topic. Users who signed up after the broadcast will not receive the message.

Basic ingredients

The basic components included in ActiveMQ are the same as those in JMS:

  1. Broker, message broker, represents the message queue server entity, accepts client connections, and provides core services for message communication.
  2. Producer, news producer, business initiator, responsible for producing and delivering news to brokers.
  3. Consumer, message consumer, business processor is responsible for receiving messages from the broker and processing business logic.
  4. Topic, Topic and Publication and Subscription messages in one unified collection location. Different manufacturers send messages to Topic, which are distributed by brokers to different subscribers in order to realize the message transmission.
  5. Queue, Queue In point-to-point mode, a specific producer sends messages to a specific queue and consumers subscribe to a specific queue to receive messages and perform business logic processing.
  6. The message, the message text, is a data packet that is encoded in a fixed format that is defined by various communication protocols in order to encapsulate business data and to realize the message transmission.

Since these concepts were introduced in JMS, they are not presented in detail here.


The main function of ActiveMQ Broker is to provide a communication mechanism for client applications. For this reason, ActiveMQ provides a connection mechanism and uses a connector to describe that connection mechanism. There are two types of connectors in ActiveMQ: one is the transport connector that is used for communication between the client and the message broker server (client-to-broker), and the other is the transport connector that is used between the message broker server (broker) becomes -to-broker) communication network connection (network connection). The connector is represented by URI (Uniform Resource Locator) and the URI format is: schema name represents the protocol, for example: foo: // username: [email protected]: 8042 / over / there / index.dtb? = Animal & name = narwhal # nose

The schema part is foo, the hierarchical part is username: [email protected]: 8042 / over / there / index.dtb, the query is type = animal & name = narwhal and the fragment is nose.

  1. Transmission Connector To exchange messages, both the message producer and the message consumer (collectively known as the client) must connect to the message proxy server. This communication between the client and the message proxy server takes place through transport connections. In many cases, users have different needs when connecting to the message broker. Some pay more attention to performance and others to safety. Therefore, ActiveMQ offers a number of connection protocols to choose from to cover these usage scenarios. From the message agent's point of view, the transport connector is used to process and monitor client connections. Check the ActiveMQ demo configuration file (/examples/conf/activemq-demo.xml). The relevant configuration of the transport connection is as follows:

The transport connection is defined inElement, oneThe element defines a specific connector. However, a connector must have its own unique name and URI attributes.The attributes are optional. Currently, the communication connector connection protocols commonly used in the latest version of ActiveMQ 5.15 are: VM, TCP, UDP, Multicast, Nio, SSL, http, https, Websocket, Amqp, MQtt, Stomp, etc.

  • With VM, the client and the message server can communicate directly within the VM. The connection used is not a socket connection, but a direct local method call for the virtual machine, which avoids the network transmission overhead. The application scenario is limited to the server and the client in the same JVM.
  • tcp, the client connects to the remote messaging server over TCP.
  • udp, the client connects to the remote messaging server using UDP.
  • Multicast allows you to use multicast transmission to connect to the messaging server.
  • The functions of nio, nio, and tcp are identical, except that nio uses Java's NIO package, which provides better performance in certain scenarios.
  • With ssl, ssl, users can use SSL based on TCP.
  • With http and https, the client can establish a connection via REST or Ajax. This means that Javascript can be used to send messages directly to ActiveMQ.
  • Websocket that allows the client to connect to the messaging server using WebSocket in HTML5.
  • amqp, version 5.8 started to support.
  • mqtt, stomp, version 5.6 started to support.

The specific configuration of each protocol can be found on the official website ( In addition to the basic protocols mentioned above, ActiveMQ also supports some advanced protocols that can also be configured via URI, e.g. B. Failover and Fanout.

  • Failover is a reconnection mechanism that works at the upper level of the connection protocol described above and is used to establish reliable transmission. The configuration syntax allows any number of compound URIs to be specified. It will automatically select one of them to connect to. If the connection is unsuccessful, it continues to select other URIs to try. Example for the configuration syntax: Failover: (tcp: // localhost: 61616, tcp: // remotehost: 61616)? InitialReconnectDelay = 100
  • Fanout is a reconnecting and replicating mechanism. It also works at the top level of other connections and uses replication to replicate messages to multiple message servers. Example for the configuration syntax: fanout: (tcp: // localhost: 61629, tcp: // localhost: 61639, tcp: // localhost: 61649)
  1. Network connector In many cases the data to be processed can be very extensive. In this scenario, it is difficult to support a single server that requires clustering. It is for this reason that ActiveMQ provides network connect mode simply to connect multiple message server instances together as a whole to provide external services, thereby enhancing the general functionality of the external message service. Server instances connected in this way can share queues and consumer lists to achieve the purpose of distributed queuing. Network connectors are used to configure communication between servers.

As shown in the figure, the servers S1 and S2 are connected via NewworkConnector. Consumers C3 and C4 can receive messages sent by manufacturer P1, and consumers C1 and C2 can also receive messages sent by manufacturer P3. In order to be able to use the function of the network connector, you have to add the following configuration under the broker node in the file activemq.xml of the server S1 (provided that is the address of S2):

If so, S1 can send a message to S2, but this is only a one-way communication and the message sent to S2 cannot be sent to S1. If S1 should also receive messages sent by S2, you must add the following configuration under the broker node in the Aktivemq.xml of S2 (assuming that is the address of S1):

In this way, S1 and S2 can communicate in both directions. Currently, the network connection protocols commonly used in the latest version of ActiveMQ 5.15 are static and multicast.

  • static, static protocol used to create a static configuration for multiple agents on a network. This configuration protocol supports compound URIs (that is, URIs that contain other URIs). E.g.
  • Multicast, a multicast protocol, the message server sends its own services and also searches for other agents. This method is used to implement dynamic identification between servers instead of configuring static IP groups.

If you are interested in this section, you can read the official document:

Message store

There are two ways to distribute messages in the JMS specification: non-persistent and persistent. With non-persistent messages, JMS implementers need to ensure that they are doing their best to distribute messages. However, messages are not stored permanently. Messages that are permanently distributed must be stored permanently. Non-persistent messages are often used to send notifications or real-time data. You can choose non-persistent messages if you value system performance, and even if some messages are lost it will not affect normal business operations. After the persistent message is sent to the message server and the consumer of the current message is not executed, the message persists. Only after the message has been processed and confirmed by the message consumer is the message deleted from the message server.

ActiveMQ supports both of the above methods and also supports message recovery using intermediate state messages cached in memory. In summary, there are three types of message storage in ActiveMQ: Save to Memory, Save to File, and Save to Database. Specific Uses ActiveMQ provides a plug-in message storage mechanism that is similar to multipoint message propagation and mainly implements the following:

  • AMQ is the default message storage method in ActiveMQ 5.0 and earlier versions. It is a file-based, transaction-supported message storage solution. In this scenario, the message itself is kept in the form of a log and is stored in the data log. In addition, the messages are indexed in the log for easy retrieval of messages.
  • KahaDB is also a file-based message storage method that supports transactions. As of 5.3, KahaDB is recommended for storing messages. It offers better scalability and recoverability than AMQ message stores.
  • JDBC is based on the JDBC method of storing messages in the database. Saving messages in the database is therefore relatively slow. ActiveMQ therefore recommends combining journals for storage. It uses fast cache write technology which greatly improves performance.
  • Storage refers to the storage of all messages that should be kept. Since there is no dynamic cache here, you have to pay attention to the setting of the JVM and the memory size of the message server.
  • LevelDB. After version 5.6 the LevelDB persistence engine was started. It uses a custom index instead of the commonly used BTree index. The persistence performance is higher than with KahaDB. Although the default persistence method is KahaDB, LevelDB will be the trend. Version 5.9 also provides a data replication method based on LevelDB and Zookeeper as the preferred data replication solution for the master-slave method.

Java access to the ActiveMQ instance

There are two ways to deliver messages in the JMS specification: one is the queuing method of the peer-to-peer model and the other is the topic method of the publish-subscribe model. Let's look at a Java example of using ActiveMQ to convey messages in topics.

Introduce dependencies

The Java project must introduce the dependency of the ActiveMQ package and the JAR package version will be the same as the version of ActiveMQ you installed:

News producer

In topic mode, the news producer is used to post news. Most of the code is similar to that in queued mode. The difference is that in this example, the topic is created based on the session that consumers will target to consume messages. .

Message consumer

To demonstrate the function of sending messages to multiple subscribers in topic mode, three consumer objects are created and subscribed to the same topic. What is special is that the main thread is put to sleep for a certain period of time. The purpose is to increase consumption. The user object can still be active so that the console can print the content of the monitored message.

Start the ActiveMQ server

Is executed directly in the bin directory of ActiveMQ ActiveMQ is started

Run TopicSubscriber

You must first perform the main method of the TopicSubscriber class so that the subscribers can receive the message when the publisher publishes the message. If the execution order is reversed, the message will be published first, but no subscribers will be executed and the message will not be used. .

Run TopicPublisher

Then do the main method of the TopicPublisher class to publish 3 messages on the topic. You can then view the content of the received messages in the TopicSubscriber background:

Spring integrates ActiveMQ

Obviously, if you are using native ActiveMQ API development in the actual project, it is more elaborate. The code for creating connection factories and creating connections can be extracted and unified by the framework. Spring also thought of these things and helped us with them. ActiveMQ fully supports Spring-based configuration of the JMS client and server. The following example shows how to use queue mode and topic mode to deliver messages in Spring.

Introduce dependencies

In addition to the Activemq package, Spring should add JMS packages to the project. We use a lot of system resources to create Connection, Session and ProducerConnection pool To reuse these resources, add the dependency on activemq-pool as well.

Spring configuration file

The Java code in the following project example uses annotations as they are also used by many programmers today. So define the path of the annotation scan package at the top of the configuration file, you can change the package name according to your actual situation. All of the Java code in this example is placed under the package.

Next, a JMS factory bean is defined using a pooled connection factory class. In effect, connection pooling functionality is added to the ActiveMQ internal connection factory. The internal configuration shows that it is correctfunctional encapsulation and the class is more familiar. It is used when creating the connection factory in the Java Access ActiveMQ example above. The BrokerURL property is configured to connect to the server protocol and address. The following cachingConnectionFactory is often used in the actual project code. It is another level of improvement for the connection factory. The connection caching feature is used to improve efficiency. Readers can use them as needed.

jmsTemplate is Spring's solution for the long and repetitive code during JMS access. The two main attributes that need to be configured are connectionFactory and messageConverter. Connections, sessions, and other objects are obtained through connectionFactory. messageConverter is the configuration message. The converter does this work because it usually requires preprocessing and postprocessing before and after sending the message. In this way, the actual code sends and receives messages directly through jmsTemplate. Every time a message is sent and received, the creation of a connection factory, connection, and session are done by the Spring framework.

With the JMS template, you also need to know the queue and the topic as the actual destination for sending and receiving messages. Next we define testQueue and testTopic as examples of the two modes. When you receive messages asynchronously, you must specify the implementation class of the MessageListener. Therefore, queueListener is defined as a listener for receiving messages asynchronously in queued mode. Topic1Listener and topic2Listener are used as listeners for the asynchronous reception of messages in topic mode. Topic mode uses two listeners. To demonstrate that multiple consumers can receive messages. The final queueContainer, topic1Container, and topic2Container are used to bind message listeners to specific message destinations.

Intelligence service

The following is a message service class that uses JMS templates to process messages

@Service declares this class as a service, and many service codes in actual projects are similar. Directly import the jmsTemplate defined in the configuration file above into the MessageService class via Resource Annotations and you can use it directly. TestQueue and testTopic are similar. The service class directly introduces the queues and topics defined in the configuration file. The focus is on the following two methods of sending messages: sendQueueMessage sends messages to the queue and sendTopicMessage sends messages to the topic. Both modes use the send method of jmsTemplate. The first parameter of the send method isType, which indicates the destination of the message. through with inherited interface, so this method is applicable to both queue mode and topic mode. The second parameter of the send method is Here an anonymous inner class is used to create an object and a text message is created from the supported session object so that the message can be sent. You can see that the code to send messages through the Spring framework is much cleaner than the previous Java code samples, whether it's a queue or a topic.

Message listener class

The queue message listener checks when the message is received to see if it is a text message type and prints the content if it is.

The topic listener's code is similar to that of the queue listener, except that different strings indicate the current messages received from different listeners while printing.

Start application

To demonstrate an example, I wrote a StartApplication class, loaded Spring into the main method, and called the sendQueueMessage and sendTopicMessage methods to send messages after getting the MessageService service.

After starting the activeMQ service, run the StartApplication class and see the received text message in the console:

The queue listener listened to a message and the two topic listeners listened to two messages.