Home Java javaTutorial Using HornetQ for message processing in Java API development

Using HornetQ for message processing in Java API development

Jun 17, 2023 pm 11:27 PM
java api hornetq Message processing

Using HornetQ for message processing in Java API development

With the rapid development of the Internet, a large number of information interactions have emerged, and message queues have become an important means to solve problems such as high concurrency, high availability, and asynchronous processing. HornetQ is a high-performance, high-availability open source messaging middleware based on the JMS protocol developed by JBoss. This article will introduce how to use HornetQ for message processing in Java API development.

1. Quick Start

  1. Download HornetQ

The official website of HornetQ (http://hornetq.apache.org/downloads.html) provides Download packages in multiple formats, choose HornetQ-2.4.0.Final-bin.tar.gz here.

  1. Installing HornetQ

After the download is complete, unzip HornetQ-2.4.0.Final-bin.tar.gz to a local folder.

  1. Start HornetQ

Enter the bin directory of HornetQ and execute the following command:

 ./run.sh

The following log appears The information indicates that the HornetQ service was successfully started:

 11:14:21,867 INFO [ServerImpl] Starting HornetQ Server
 11:14:21,986 INFO [JournalStorageManager] Using NIO Journal
 11:14:22,626 INFO [NettyAcceptor] Started Netty Acceptor version #{version}
 11:14:22,697 INFO [HornetQServerImpl] HornetQ Server version #{version} [${name}] started

  1. Deploy HornetQ console

Put HornetQ's hornetq-console.war into Tomcat's webapps directory, start Tomcat, and access the HornetQ console through http://localhost:8080/hornetq-console.

2. The use of HornetQ

  1. Publishing and receiving messages

HornetQ’s publish and subscribe model is based on Topic, and the publishing end publishes to a certain Topic message, and multiple receivers can subscribe to this Topic at the same time, and the receiver can receive messages published by multiple publishers.

(1) Message publishing end

First create a publishing end (Publisher) to send messages, the code is as follows:

public class Publisher {

    public static void main(String[] args) throws Exception {

        // 初始化连接工厂等配置信息
        ConnectionFactory connectionFactory = HornetQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.CF, new TransportConfiguration(NettyConnectorFactory.class.getName()));
        JMSContext jmsContext = connectionFactory.createContext();

        // 发送消息
        JMSProducer producer = jmsContext.createProducer();
        Destination destination = HornetQJMSClient.createTopic("exampleTopic");
        producer.send(destination, "Hello, HornetQ!");

        // 关闭连接
        jmsContext.close();
    }
}
Copy after login

(2) Message receiving end

Create another receiver (Subscriber) to receive the message and print it out. The code is as follows:

public class Subscriber {

    public static void main(String[] args) throws Exception {

        // 初始化连接工厂等配置信息
        ConnectionFactory connectionFactory = HornetQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.CF, new TransportConfiguration(NettyConnectorFactory.class.getName()));
        JMSContext jmsContext = connectionFactory.createContext();

        // 创建消费者
        Destination destination = HornetQJMSClient.createTopic("exampleTopic");
        JMSConsumer consumer = jmsContext.createConsumer(destination);

        // 接收消息并打印
        String message = null;
        do {
            message = consumer.receiveBody(String.class, 1000);
            System.out.println("Received message: " + message);
        } while (message != null);

        // 关闭连接
        jmsContext.close();
    }
}
Copy after login

After running the publisher and receiver, you can view the messages sent by the publisher on the HornetQ console , as shown in the figure below:

  1. Message persistence

HornetQ supports persistent storage of messages, which means that even if HornetQ is down, the message can be guaranteed to be persisted. lost.

(1) Sender

We need to set the persistence of the message to DeliveryMode.PERSISTENT, as follows:

public class Publisher {

    public static void main(String[] args) throws Exception {

        ConnectionFactory connectionFactory = HornetQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.CF, new TransportConfiguration(NettyConnectorFactory.class.getName()));
        JMSContext jmsContext = connectionFactory.createContext();

        // 设定持久性
        JMSProducer producer = jmsContext.createProducer();
        destination = HornetQJMSClient.createTopic("exampleTopic");
        producer.setDeliveryMode(DeliveryMode.PERSISTENT);

        // 发送消息
        producer.send(destination, "Hello, HornetQ!");

        jmsContext.close();
    }
}
Copy after login

(2) Receiver

HornetQ has persisted messages by default, so there is no need to perform specific configuration on the receiver side. Just continue to use the Subscriber class in the previous section.

  1. Cluster Mode

HornetQ features high availability and can be run in cluster mode to ensure message reliability and high concurrency. The following are the steps to implement HornetQ cluster mode:

(1) Copy the HornetQ directory and create a new folder

Copy the HornetQ directory and rename it to HornetQ2, and then create a new file named cluster folder, and copy all the data directory, log directory, tmp directory and other folders under the HornetQ2 directory to the cluster folder.

(2) Modify the configuration file

In the examples/configs/clustered configuration folder under the HornetQ directory, copy the hq-configuration.xml file and server0 and server1 folders to the HornetQ2 directory , and modify the hornetq-configuration.xml file in the server0 folder as follows:

  (a) Modify the node name to server0

  (b) Change the cluster-connections in Change server-username and server-password to "guest"

 (c) Modify the connector address to the local IP address, such as 192.168.1.1

 (d) Change use under jms-configuration -ha is set to true

As shown below:

<configuration xmlns="urn:hornetq"
               xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
               xsi:schemaLocation="urn:hornetq /schema/hornetq-configuration.xsd">
    <cluster-password>guest</cluster-password>
    <paging-directory>${data.dir:../data}/paging</paging-directory>
    <bindings-directory>${data.dir:../data}/bindings</bindings-directory>
    <journal-directory>${data.dir:../data}/journal</journal-directory>
    <large-messages-directory>${data.dir:../data}/large-messages</large-messages-directory>
    <journal-type>NIO</journal-type>
    <journal-datasync>true</journal-datasync>
    <journal-min-files>2</journal-min-files>
    <journal-pool-files>10</journal-pool-files>
    <journal-file-size>10240</journal-file-size>
    <journal-buffer-timeout>28000</journal-buffer-timeout>
    <journal-max-io>1</journal-max-io>
    <disk-scan-period>5000</disk-scan-period>
    <max-disk-usage>90</max-disk-usage>
    <critical-analyzer>true</critical-analyzer>
    <critical-analyzer-timeout>120000</critical-analyzer-timeout>
    <critical-analyzer-check-period>60000</critical-analyzer-check-period>
    <critical-analyzer-policy>HALT</critical-analyzer-policy>
    <page-sync-timeout>1628000</page-sync-timeout>
    <global-max-size>100Mb</global-max-size>
    <connectors>
        <connector name="netty">
            <factory-class>org.hornetq.core.remoting.impl.netty.NettyConnectorFactory</factory-class>
            <param key="host" value="192.168.1.1"/>
            <param key="port" value="5445"/>
        </connector>
    </connectors>
    <acceptors>
        <acceptor name="netty">
            <factory-class>org.hornetq.core.remoting.impl.netty.NettyAcceptorFactory</factory-class>
            <param key="host" value="192.168.1.1"/>
            <param key="port" value="5545"/>
        </acceptor>
    </acceptors>
    <cluster-connections>
        <cluster-connection name="my-cluster">
            <address>jms</address>
            <connector-ref>netty</connector-ref>
            <retry-interval>500</retry-interval>
            <use-duplicate-detection>true</use-duplicate-detection>
            <forward-when-no-consumers>true</forward-when-no-consumers>
            <max-hops>1</max-hops>
            <discovery-group-ref discovery-group-name="my-discovery-group"/>
            <static-connectors>
                <connector-ref>netty</connector-ref>
            </static-connectors>
        </cluster-connection>
    </cluster-connections>
    <ha-policy>
        <replication>
            <slave>
                <allow-failback>true</allow-failback>
                <failback-delay>5000</failback-delay>
                <max-saved-replicated-journals-size>1000000</max-saved-replicated-journals-size>
                <restart-backup>true</restart-backup>
            </slave>
        </replication>
    </ha-policy>
</configuration>
Copy after login

Then modify the hornetq-configuration.xml file in the server1 folder in the same way, changing server0 to server1.

(3) Start HornetQ

Execute the run.sh command in the bin directory of HornetQ and HornetQ2 to start the HornetQ process. At this time, the two HornetQ nodes form a cluster, which can be used through HornetQ Check the console.

3. Summary

Through the introduction of this article, we have learned about the basic use of HornetQ and the configuration method of cluster mode. Using HornetQ can easily solve the problem of message interaction and improve the robustness and concurrency of the system. At the same time, HornetQ also supports multiple messaging modes, rich message persistence mechanisms, extension plug-ins and other features, which can be selected and configured according to actual needs.

The above is the detailed content of Using HornetQ for message processing in Java API development. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1267
29
C# Tutorial
1239
24
Using Imgscalr for image processing in Java API development Using Imgscalr for image processing in Java API development Jun 18, 2023 am 08:40 AM

Using Imgscalr for image processing in Java API development With the development of mobile Internet and the popularity of Internet advertising, images have become an indispensable element in many applications. Whether it is displaying products, building social circles, or enhancing user experience, images play an important role. In applications, it is often necessary to perform operations such as cropping, scaling, and rotating images, which requires the use of some image processing tools. Imgscalr is a very commonly used image in Java API development.

How to implement image verification code in Java API development How to implement image verification code in Java API development Jun 18, 2023 am 09:22 AM

With the rapid development of Internet technology, in order to ensure system security, verification codes have become an essential part of every system. Among them, picture verification code is favored by developers due to its ease of use and security. This article will introduce the specific method of implementing image verification code in JavaAPI development. 1. What is picture verification code? Picture verification code is a way of human-machine verification through pictures. It usually consists of a random combination of pictures containing numbers, letters, symbols, etc., which improves the security of the system. Its working principle includes

What are the free API interface websites? What are the free API interface websites? Jan 05, 2024 am 11:33 AM

Free api interface website: 1. UomgAPI: a platform that provides stable and fast free API services, with over 100 API interfaces; 2. free-api: provides multiple free API interfaces; 3. JSON API: provides free data API interface; 4. AutoNavi Open Platform: Provides map-related API interfaces; 5. Face recognition Face++: Provides face recognition-related API interfaces; 6. Speed ​​data: Provides over a hundred free API interfaces, suitable for various needs In the case of data sources; 7. Aggregate data, etc.

Using GreenMail for email testing in Java API development Using GreenMail for email testing in Java API development Jun 18, 2023 pm 02:22 PM

Java API is a widely used development language for developing web applications, desktop applications, mobile applications, etc. In JavaAPI development, email testing is essential because email communication is one of the main communication methods in modern society. Therefore, developers need to use some tools to test whether their emails are functioning properly. This article will introduce an open source software called GreenMail, which can be used in JavaAPI development for email testing. Green

What are the common protocols for Java network programming? What are the common protocols for Java network programming? Apr 15, 2024 am 11:33 AM

Commonly used protocols in Java network programming include: TCP/IP: used for reliable data transmission and connection management. HTTP: used for web data transmission. HTTPS: A secure version of HTTP that uses encryption to transmit data. UDP: For fast but unstable data transfer. JDBC: used to interact with relational databases.

Using Jgroups for distributed communication in Java API development Using Jgroups for distributed communication in Java API development Jun 18, 2023 pm 11:04 PM

Using JGroups for distributed communication in JavaAPI development With the rapid development of the Internet and the popularity of cloud computing, distributed systems have become one of the important trends in today's Internet development. In a distributed system, different nodes need to communicate and collaborate with each other to achieve high availability, high performance, high scalability and other characteristics of the distributed system. Distributed communication is a crucial part of it. JGroups is a Java library that supports multicast and distributed collaboration. It provides a series of

JAX-RS vs. Spring MVC: A battle between RESTful giants JAX-RS vs. Spring MVC: A battle between RESTful giants Feb 29, 2024 pm 05:16 PM

Introduction RESTful APIs have become an integral part of modern WEB applications. They provide a standardized approach to creating and using Web services, thereby improving portability, scalability, and ease of use. In the Java ecosystem, JAX-RS and springmvc are the two most popular frameworks for building RESTful APIs. This article will take an in-depth look at both frameworks, comparing their features, advantages, and disadvantages to help you make an informed decision. JAX-RS: JAX-RSAPI JAX-RS (JavaAPI for RESTful Web Services) is a standard JAX-RSAPI developed by JavaEE for developing REST

RESTful interface design in Java API development RESTful interface design in Java API development Jun 18, 2023 am 08:31 AM

With the development of Internet technology, RESTful style API design has become the most popular design method. As a major programming language, Java is increasingly playing an important role in the development of RESTful interfaces. In JavaAPI development, how to design an excellent RESTful interface has become a problem that requires us to think deeply. Basic principles of RESTful interface First, we need to understand the basic principles of RESTful interface. REST is Re

See all articles