SpringBoot整合activeMq消息中間件

消息中間件常用的兩個是activeMq以及rabbitmq,這裏介紹的只是springBoot整合activeMq實現郵件發送的一個方式
activeMq的項目主要有兩個部分,一個是消費者另一個就是消息的生成者,生成者也就是項目中的消費者部分進行的業務邏輯處理的部分,通過將這部分數據發送到activeMq中進行隊列或者主題排隊,依次分發隊列或者統一分發給每一個隊列,進行數據消費,實現業務處理功能
安裝好activeMq之後,只需要在SpringBoot中進行配置好連接信息,對於發送郵件的其他使用規則,可以參考本人的郵件發送使用(springMVC整合的)雖然是springMVC的,但是使用規則與在SpringBoot中也是差不多的,我這裏也會附上代碼,供大家參考
activeMq的消費者端代碼(consumer)

package com.active.consumer;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.springframework.stereotype.Component;

import javax.jms.*;

/**
 * @description:  隊列消息消費端   (點對點消費端)
 * @author: liuhui
 * @createDate: 2020/3/27
 * @version: 1.0
 */
@Component
public class Consumer {
//    @JmsListener(destination = "${my_queue}")
//    public void receive(String msg){
//        System.out.println("點對點模式成功獲取消息  msg:"+msg);
//    }
//    @Autowired
//    JavaMailSender javaMailSender;      /*郵件發送類*/
//    @JmsListener(destination = "${my_topic}")
//    public void receive(String msg){
//        if(StringUtils.isEmpty(msg)) return;
////        轉json
//        JSONObject jsonObject = new JSONObject().parseObject(msg);
////        獲取json數據
//        String userName = jsonObject.getString("userName");
//        String email = jsonObject.getString("email");
//        sendEmail(userName,email);
//        System.out.println("發佈訂閱模式成功獲取消息  msg:"+msg);
//    }
//    /*郵件發送工具類*/
//    public void sendEmail(String userName,String email){
//        /*郵件內容*/
//        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
//        simpleMailMessage.setFrom("[email protected]");   /*郵件發送者*/
//        simpleMailMessage.setTo(email);  /*郵件接受者*/
//        simpleMailMessage.setSubject("暉哥測試郵件發送,不要迷戀哥哥");    /*郵件標題*/
//        simpleMailMessage.setText("恭喜你,"+userName+"!你見證了我的學習成果!");  /*郵件內容*/
//        /*郵件發送*/
//        javaMailSender.send(simpleMailMessage);
//        System.out.println("郵件發送成功");
//    }


    /*
     *  activeMq默認是自動簽收的
     * 現在改爲手動簽收模式和事務模式(這裏用的是點對點,發佈訂閱是一樣的書寫規範)
     * 這是測試代碼,開發情況可在配置文件中配置)
     * 生成者以事務進行生成消息,消費者也需使用事務消費消息
     * 生成者以手動簽收發送消息,消費者就需要通過手動簽收迴應生產者消息消費成功
     * 簽收方式是在消費者中進行設置,生成者中無需改變
     * 消費者無需關閉隊列連接
     */
    //    連接地址
    private static String url = "tcp://192.168.42.123:61617";
    //    隊列名稱
    private static String queueName = "text_queue";

    public static void main(String[] args) {
//        1.建立連接工廠  密碼默認是admin admin  這裏可以設置密碼
        ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory("admin","123456",url);
        Connection connection = null;
        try {
            //              2.創建連接
            connection = activeMQConnectionFactory.createConnection();
            connection.start(); /*啓動連接*/
            //             3.創建會話,參數1 設置事務提交是否開啓、參數2 消息方式是否採用自動簽收
            //Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); /*事務簽收*/
            Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); /*手動簽收*/
            //            4.創建隊列
            Queue queue = session.createQueue(queueName);
            //            5.創建消費者
            MessageConsumer consumer = session.createConsumer(queue);
            //              6.監聽消息
            consumer.setMessageListener(new MessageListener() {
                @Override
                public void onMessage(Message message) {
                    //      7.獲取消息
                    TextMessage textMessage = (TextMessage) message;
                    System.out.println("消費者獲取內容:"+textMessage);
                    try {
                        /*手動簽收消息迴應生成者*/
                        textMessage.acknowledge();
//                        8.事務提交
//                        session.commit();

                    } catch (JMSException e) {
                        e.printStackTrace();
                    }
                }
            });
        } catch (JMSException e) {
            e.printStackTrace();
        }
    }
}

這裏分別提供了activeMq的4中方式,有點對點的發送方式,有發佈訂閱的發送方式,有手動簽收的接收方式同時也有事務的接收方式,代碼中都有具體的註釋,可以參考使用在activeMq中默認的方式是自動簽收的,所有對於自動簽收的方式就不需要設置了
activeMq的提供端(Producer )

package com.activemq.activemq.producer;

import com.alibaba.fastjson.JSONObject;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.scheduling.annotation.Scheduled;

import javax.jms.*;

/**
 * @description:    消息生成者  向activemq中發送消息
 * @author: liuhui
 * @createDate: 2020/3/26
 * @version: 1.0
 */

@Configuration
public class Producer {
    /**
     * 點對點模式
     */
    @Autowired
    private JmsMessagingTemplate jmsMessagingTemplate;      /*隊列模板*/
    @Autowired
    private Queue queue;
    /*通過定時任務,每隔5s鍾向activemq中發送一個消息*/
    @Scheduled(fixedDelay = 5000)   /*定時任務,每隔5s發送一個消息  單位是ms   5000ms = 5s */
    public void send(){
        String msg = System.currentTimeMillis()+"";
        jmsMessagingTemplate.convertAndSend(queue,msg);
        System.out.println("採用點對點模式+msg:"+msg);
    }


    /**
     * 發佈訂閱模式
     */
//    @Autowired
//    private Topic topic;
//    通過定時任務,每隔5s鍾向activemq中發送一個消息
//    @Scheduled(fixedDelay = 5000)   //定時任務,每隔5s發送一個消息  單位是ms   5000ms = 5s
//    public void send(){
//        String userName = "郭鵬麗";
//        JSONObject jsonObject = new JSONObject();
//        jsonObject.put("userName",userName);
//        jsonObject.put("email","[email protected]");
//        String msg = jsonObject.toJSONString();
//        jmsMessagingTemplate.convertAndSend(topic,msg);
//        System.out.println("採用發佈訂閱模式+msg:"+msg);
//    }


    /*
     *  activeMq默認是自動簽收的
     * 現在改爲手動簽收模式和事務模式(這裏用的是點對點,發佈訂閱是一樣的書寫規範)
     * 這是測試代碼,開發情況可在配置文件中配置)
     * 生成者以事務進行生成消息,消費者也需使用事務消費消息
     * 生成者以手動簽收發送消息,消費者就需要通過手動簽收迴應生產者消息消費成功
     */
//    連接地址
    private static String url = "tcp://192.168.42.123:61617";
//    隊列名稱
    private static String queueName = "text_queue";
    public static void main(String[] args) throws JMSException {
        //                  1.建立連接工廠  密碼默認是admin admin  這裏可以設置密碼
        ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory("admin","123456",url);
        Connection connection = null;
        try {
            //              2.創建連接
            connection = activeMQConnectionFactory.createConnection();
            connection.start(); /*啓動連接*/
            //             3.創建會話,參數1 設置事務提交是否開啓、參數2 消息方式是否採用自動簽收
//            Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); /*事務簽收*/
            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); /*手動簽收*/
            //            4.創建隊列
            Queue queue = session.createQueue(queueName);
            //            5.創建生成者
            MessageProducer producer = session.createProducer(queue);
            //           6.設置消息持久化
            producer.setDeliveryMode(DeliveryMode.PERSISTENT);
            for (int i = 0; i < 10 ; i++) {
                //          7.生成消息
                TextMessage textMessage = session.createTextMessage("發送消息:"+i);
                //          8.發送消息
                producer.send(textMessage);
                //          9.事務提交      (手動簽收模式,無需開啓事務提交)
//                session.commit();
                System.out.println("消息發送成功!"+textMessage);
            }
        } catch (JMSException e) {
            e.printStackTrace();
        }finally {
//            關閉連接
            connection.close();
        }
    }
}

在使用activeMq的時候,我們也需要進行書寫一個bean,通過bean注入到spring的容器中,通過容器進行使用對activeMq的隊列發送消息,這裏還採用一個定時任務進行數據的發送,用來模擬消息不斷生成的環境,在項目實踐中,可以不用使用這個定時任務,開啓定時任務還需要在SpringBoot中的啓動類中進行配置

package com.activemq.activemq;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@EnableScheduling       /*開啓定時任務*/
public class ActivemqApplication {

    public static void main(String[] args) {
        SpringApplication.run(ActivemqApplication.class, args);
    }

}

activeMq的配置類(config)

package com.activemq.activemq.utils;

import org.apache.activemq.command.ActiveMQQueue;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.jms.Queue;
/**
 * 隊列消息提供者
 */

/**
 * @description:        activemq 配置類  這裏配置隊列信息
 * @author: liuhui
 * @createDate: 2020/3/26
 * @version: 1.0
 */
@Configuration  /*標註爲配置類*/
public class ConfigQueue {
    /*點對點模式*/
    @Value("${my_queue}")
    private String myQueue;
    /*1.將隊列注入到SpringBoot容器中*/
    @Bean
    public Queue queue(){
        return new ActiveMQQueue(myQueue);
    }

//    /*發佈訂閱模式*/
//    @Value("${my_topic}")
//    private String myTopic;
//    /*1.將隊列注入到SpringBoot容器中*/
//    @Bean
//    public Topic queue(){
//        return new ActiveMQTopic(myTopic);
//    }
}

配置類也主要是進行配置activeMq的兩種隊列發送發送方式,點對點模式,發佈訂閱模式
到這裏,activeMq代碼就已經書寫完成,下面貼上配置文件,和email發送用的配置文件,就可將代碼複製下來啓動試驗了
provide端的yml文件配置

server:
  port: 9896
spring:
  activemq:
    broker-url: tcp://192.168.42.123:61617?jms.optimizeAcknowledge=true&jms.optimizeAcknowledgeTimeOut=30000&jms.redeliveryPolicy.maximumRedeliveries=10
    user: admin
    password: 123456
#    點對點模式
my_queue: springBoot1.5.9_my_queue
#發佈訂閱模式
#my_topic: springBoot1.5.9_my_topic



consumer端的yml文件配置

server:
  port: 9895
spring:
  activemq:
    broker-url: tcp://192.168.42.123:61617?jms.optimizeAcknowledge=true&jms.optimizeAcknowledgeTimeOut=30000&jms.redeliveryPolicy.maximumRedeliveries=10
    user: admin
    password: 123456
  #    SpringBoot在整合activemq的發佈訂閱模式默認沒有開啓,需要手動開啓
  jms:
    pub-sub-domain: true
  mail:
#    163郵件服務
    host: smtp.163.com
#    發送郵件賬號
    username: *****
#    郵箱授權碼
    password: ***********
#    編碼格式
    default-encoding: utf-8
#    點對點
#my_queue: springBoot1.5.9_my_queue
#發佈訂閱
my_topic: springBoot1.5.9_my_topic



password是郵箱的授權嗎,具體使用,可以看上面推薦的博客進行配置

最後貼上pom文件,進行jar包管理下載

 <!--email jar start-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
        </dependency>
        <!--email end-->
         <!--json格式轉換包 start-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.60</version>
        </dependency>
        <!--json格式轉換包 end-->
         <!--json格式轉換包 start-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.60</version>
        </dependency>
        <!--json格式轉換包 end-->

那個email的jar包只需要在consumer中進行配置

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章