Spring quickly builds JMS

1. Introduction

JMS (Java Message Service) java asynchronous message service

1. What is JMS?
jms is a standard that defines a common API for using messages, similar to jdbc, users can use the same interface to operate different message service implementations

2. Application scenarios of JMS?
jms represents asynchronous communication between applications, corresponding to synchronous communication. The so-called synchronous communication means that after the message is sent, the client needs to wait until the server responds, even if the server just returns an empty message. Asynchronous messaging is similar to mailing a letter, when we put the letter in the mailbox and assume it will be delivered correctly, we don't have to wait for a reply, or even care when the letter is sent, and we trust that the letter will be processed correctly! Asynchronous messaging means that we send the message to the message broker server, and assume that the message can definitely be delivered to the specified destination, believing that the message will definitely be processed.

3. Concepts involved in JMS?

  • jms is a specification. Since it is a specification, there must be services that implement the specification, such as (ActiveMQ)
  • Message broker server (similar to post office)
  • Destinations (similar to recipient addresses) include peer-to-peer queues and publish/subscribe topics
  • We send the message to the proxy server, and the proxy server sends it to the specified destination, it's that simple!

4. Introduction of message queue and publish-subscribe
Message queue is point-to-point. When a message is sent, there will be a service that can receive it, but there is more than one service concerned, and the sender does not care who receives the message. The benefit of this is that we can improve performance by adding more receivers

Publish and subscribe. When a message is published, all users who have subscribed to the message topic can receive the message, but the sender does not know who subscribed to his message. Imagine a scenario, when a new employee comes to the company, the HR department will Create some files for the employee, the financial department will register the salary information for the employee, and the logistics department will assign the employee office supplies, etc. That is to say, the same information can be processed differently when obtained by different applications.


2. Start with a helloworld

Don't rush to step by step.
The first step is to download ActiveMQ (the download address can be found on the Internet!) The
second step, after decompression, start the proxy server in the bin directory as shown in the figure


Start the proxy server


The third step is to copy activemq-broker-5.9.1.jar and activemq-client-5.9.1.jar in the decompressed lib directory into your classpath, or introduce the dependencies of the corresponding versions in your pom file

           <dependency>
                <groupId>org.apache.activemq</groupId>
                <artifactId>activemq-broker</artifactId>
                <version>5.9.1</version>
            </dependency>
            <dependency>
                <groupId>org.apache.activemq</groupId>
                <artifactId>activemq-client</artifactId>
                <version>5.9.1</version>
            </dependency>

The fourth step, sender code (producer)

//创建连接工厂 ActiveMQ服务默认的端口号是:61616
 ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://localhost:61616");
        Connection conn = null;
        Session session = null;
        try {
       //创建连接
            conn = connectionFactory.createConnection();
            conn.start();
      //创建会话
            session = conn.createSession(false,session.AUTO_ACKNOWLEDGE);
      //创建目的地(点对点目的地,发布订阅是(ActiveMQTopic对象))
            Destination destination = new ActiveMQQueue("gamelife.alert.queue");
      //创建消息发送者
            MessageProducer producer = session.createProducer(destination);
        //创建文本消息
            TextMessage message = new ActiveMQTextMessage();
            message.setText("Hello world!");
        //发送消息
            producer.send(destination,message);
        } catch (JMSException e) {
            e.printStackTrace();
        } finally {
        //资源不要忘了关闭
            try {
                if (conn != null) {
                    conn.close();
                }
                if (session != null) {
                    session.close();
                }
            } catch (JMSException e) {
                throw new RuntimeException(e);
            }
        }

Step 5. Receiver Code (Consumer)

        ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://localhost:61616");
        Connection conn = null;
        Session session = null;
        try {
            conn = connectionFactory.createConnection();
            conn.start();
            session = conn.createSession(false,session.AUTO_ACKNOWLEDGE);
            Destination destination = new ActiveMQQueue("gamelife.alert.queue");
          //创建消息接收者
            MessageConsumer consumer = session.createConsumer(destination);
          //接收消息
            TextMessage message = (TextMessage) consumer.receive();
            System.out.println(message.getText());
        } catch (JMSException e) {
            e.printStackTrace();
        } finally {
            try {
                if (conn != null) {
                    conn.close();
                }
                if (session != null) {
                    session.close();
                }
            } catch (JMSException e) {
                throw new RuntimeException(e);
            }
        }

This completes a simple helloworld

Third, use spring's JmsTemplate to eliminate duplicate code

The first step, configure ConnectionFactory, and JmsTemplate

    <bean id="connectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
        <property name="brokerURL" value="tcp://localhost:61616"/>
    </bean>
    <bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
        <property name="connectionFactory" ref="connectionFactory"/>
    </bean>

The second step, send the message code

       ApplicationContext context = new ClassPathXmlApplicationContext("/conf/applicationContext.xml");
        JmsTemplate jmsTemplate = (JmsTemplate) context.getBean("jmsTemplate");
//可以通过convertAndSend()直接发送实现了序列化接口的对象,第一个参数是目的地,默认是消息队列如果希望是发布订阅的主题可以传一个对象
        jmsTemplate.convertAndSend("gamelife.alert.queue",new User("username","password"));

The third step, receive the message

        ApplicationContext context = new ClassPathXmlApplicationContext("/conf/applicationContext.xml");
        JmsTemplate jmsTemplate = (JmsTemplate) context.getBean("jmsTemplate");
        System.out.println(jmsTemplate==null);
        User user= (User) jmsTemplate.receiveAndConvert("gamelife.alert.queue");
        System.out.println(user.getUsername());

finished.

Fourth, use spring to create a message-driven POJO

First of all, what is wrong with the previous operation? That is, every time the receiver goes to get a message, the receive method will block until a message arrives. This is not what we want. We need an event-driven message system, which means that when there is a message, it will automatically call our method.
The first step is to create an object for listening to messages

//仅仅是一个简单的实现了MessageListener接口的POJO
public class JmsHandler implements MessageListener{

    public void onMessage(Message message) {
        try {
            User user = (User) ((ObjectMessage) message).getObject();
            System.out.println(user.getUsername());
            System.out.println(user.getPassword());
        } catch (JMSException e) {
            e.printStackTrace();
        }
    }
}

The second step, configure the message listener object**

<bean id="jmsHandler" class="jmslistener.JmsHandler"></bean>
<jms:listener-container>
        <jms:listener destination="gamelife.alert.queue" ref="jmsHandler" />
    </jms:listener-container>

After the server is started, the corresponding method will be automatically called when a message arrives

Even if it is over here, let’s go and build your own JMS server. The publish-subscribe model will not type duplicate code. It’s just that the Destination (ActiveMQTopic) and the object are different. It’s fine to follow the IDE’s prompts.

 

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326887126&siteId=291194637