發送郵件及消息中間件

郵件發送過程java

協議:規定了數據傳輸的格式。web

工具類spring

/**
 *
 * @param to            : 郵件接收者
 * @param subject       :主題
 * @param content       :郵件正文
 * @throws Exception
 */
public static void sendMsg(String to ,String subject ,String content) throws Exception{
   //1.發送郵件設置
   Properties props = new Properties();
   props.setProperty("mail.smtp.host", "smtp.sina.com");  //設置主機地址   smtp.qq.com    smtp.sina.com
   props.setProperty("mail.smtp.auth", "true");//認證

   //2.產生一個用於郵件發送的Session對象
   Session session = Session.getInstance(props);

   //3.產生一個郵件的消息對象
   MimeMessage message = new MimeMessage(session);

   //4.設置消息的發送者
   Address fromAddr = new InternetAddress("004@sina.com");
   message.setFrom(fromAddr);

   //5.設置消息的接收者
   Address toAddr = new InternetAddress(to);
   //TO 直接發送  CC抄送    BCC密送
   message.setRecipient(MimeMessage.RecipientType.TO, toAddr);

   //6.設置主題
   message.setSubject(subject);
   //7.設置正文
   message.setText(content);

   //8.準備發送,獲得火箭
   Transport transport = session.getTransport("smtp");
   //9.設置火箭的發射目標
   transport.connect("smtp.sina.com", "004@sina.com", "loveyou");
   //10.發送
   transport.sendMessage(message, message.getAllRecipients());

   //11.關閉
   transport.close();
}

新增用戶發送郵件apache

/**
 * 新增用戶
 *      1.獲取表單數據構造user對象
 *      2.添加對應的企業屬性
 * 更新用戶
 */
@RequestMapping(value = "/edit" , name = "編輯用戶")
public String edit(User user) {
   user.setCompanyId(companyId);
   user.setCompanyName(companyName);
   //1.判斷是否具備id屬性
   if(UtilFuns.isEmpty(user.getId())) {
      String password = user.getPassword();
      //2.沒有id,保存
      userService.save(user);
      //發送郵件
      try{
         MailUtil.sendMsg(user.getEmail(),"恭喜申請成功","尊敬的xxx用戶您好:歡迎加入xxxxx,您的登陸帳號爲:"+
               user.getEmail()+",登陸密碼爲:"+password);//接收者,主體,正文
      }catch (Exception e) {
         e.printStackTrace();
      }
   }else{
      //3.具備id,更新
      userService.update(user);
   }
   return "redirect:/system/user/list.do";
}

消息中間件api

概述服務器

消息中間件利用高效可靠的消息傳遞機制進行平臺無關的數據交流,並基於數據通訊來進行分佈式系統的集成。經過提供消息傳遞和消息排隊模型,
它能夠在分佈式環境下擴展進程間的通訊。消息隊列中間件是分佈式系統中重要的組件,主要解決應用解耦,異步消息,流量削鋒等問題,
實現高性能,高可用,可伸縮和最終一致性架構。 對於消息中間件,常見的角色大體也就有 Producer(生產者)、Consumer(消費者)。

常見消息中間件session

常見的消息中間件產品:
(1 )ActiveMQ
ActiveMQ 是 Apache 出品,最流行的,能力強勁的開源消息總線。ActiveMQ 是一個徹底支持 JMS1.1 和J2EE 1.4 規範的 JMS Provider 實現。
(2)RabbitMQ
AMQP 協議的領導實現,支持多種場景。淘寶的 MySQL 集羣內部有使用它進行通信,OpenStack 開源雲平臺的通訊組件,最早在金融行業獲得運用。
(3)ZeroMQ
史上最快的消息隊列系統
(4)Kafka
Apache 下的一個子項目 。特色:高吞吐,在一臺普通的服務器上既能夠達到 10W/s 的吞吐速率;徹底的分佈式系統。適合處理海量數據。

消息的兩種模式架構

ActiveMQapp

軟件安裝dom

綠色版解壓便可

spring整合ActiveMQ

消息生產者

引入座標

<properties>
    <spring.version>5.0.2.RELEASE</spring.version>
</properties>

<dependencies>
    <!-- Spring -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jms</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.apache.activemq</groupId>
        <artifactId>activemq-all</artifactId>
        <version>5.11.2</version>
    </dependency>
    <dependency>
        <groupId>javax.jms</groupId>
        <artifactId>javax.jms-api</artifactId>
        <version>2.0.1</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
    </dependency>
</dependencies>

配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:amq="http://activemq.apache.org/schema/core"
xmlns:jms="http://www.springframework.org/schema/jms"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/jms
http://www.springframework.org/schema/jms/spring-jms.xsd
http://activemq.apache.org/schema/core
http://activemq.apache.org/schema/core/activemq-core.xsd">

<context:component-scan base-package="cn.jia"></context:component-scan>

<!--
spring和activeMq整合:經過整合JmsTemplate對象進行消息發送
-->
<!--1.鏈接工廠-->
<bean id="activeMQConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
<property name="brokerURL" value="tcp://127.0.0.1:61616"></property>
</bean>
<!--2.spring管理鏈接工廠-->
<bean id="connectionFactory" class="org.springframework.jms.connection.CachingConnectionFactory">
<property name="targetConnectionFactory" ref="activeMQConnectionFactory"></property>
</bean>
<!--3.指定目的地址:queue或者topic-->
<bean id="queue" class="org.apache.activemq.command.ActiveMQQueue">
<!--value:表示在activeMQ中建立的列表名稱-->
<constructor-arg value="test-spring-queue"></constructor-arg>
</bean>
<!--4.經過鏈接工廠建立jmstemplate-->
<bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
<property name="connectionFactory" ref="connectionFactory"></property>
</bean>

<!--3.指定目的地址:queue或者topic-->
<bean id="topic" class="org.apache.activemq.command.ActiveMQTopic">
<!--value:表示在activeMQ中建立的列表名稱-->
<constructor-arg value="test-spring-topic"></constructor-arg>
</bean>
</beans>

消息提供者java代碼

@Component
public class ActivemqProducer {

    @Autowired
    private Destination queue; //注入queue

    @Autowired
    private Destination topic; //注入topic

    @Autowired
    private JmsTemplate jmsTemplate; //注入工具類

    public void sendQueue(final String msg){
        //參數1:表示消息要傳遞到哪一個隊列中   參數2:消息建立器對象
        jmsTemplate.send(queue, new MessageCreator() {
            //session:消息對象
            public Message createMessage(Session session) throws JMSException {
                //建立一個字符串類型消息
                TextMessage textMessage = session.createTextMessage(msg);
                return textMessage;
            }
        });
    }

    public void sendTopic(final String msg){
        //參數1:表示消息要傳遞到哪一個隊列中   參數2:消息建立器對象
        jmsTemplate.send(topic, new MessageCreator() {
            //session:消息對象
            public Message createMessage(Session session) throws JMSException {
                //建立一個字符串類型消息
                TextMessage textMessage = session.createTextMessage(msg);
                return textMessage;
            }
        });
    }
}

測試

// @RunWith(SpringJUnit4ClassRunner.class)
@RunWith(SpringRunner.class)
@ContextConfiguration("classpath:applicationContext-jms.xml")
public class TestActiveMq {


    @Autowired
    private ActivemqProducer activemqProducer;

    @Test
    //測試queue
    public void test1(){
        activemqProducer.sendQueue("hello123");
    }

    @Test
    //測試topic
    public void test2(){
        activemqProducer.sendTopic("hello tom");
    }
}

消息消費者

配置文件

 <context:component-scan base-package="cn.jia"></context:component-scan>

    <!--
        spring和activeMq整合:經過整合JmsTemplate對象進行消息發送
    -->
    <!--1.鏈接工廠-->
    <bean id="activeMQConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
        <property name="brokerURL" value="tcp://127.0.0.1:61616"></property>
    </bean>
    <!--2.spring管理鏈接工廠-->
    <bean id="connectionFactory"  class="org.springframework.jms.connection.CachingConnectionFactory">
        <property name="targetConnectionFactory" ref="activeMQConnectionFactory"></property>
    </bean>

    <!--告知消費者業務類,去哪一個隊列中獲取消息-->
    <!--配置監聽器管理器
       配置的都是基於queue類型的消息監聽    -->
    <jms:listener-container destination-type="queue" connection-factory="connectionFactory">
        <jms:listener destination="test-spring-queue" ref="activeMqConsumer"/>
    </jms:listener-container>

    <!--告知消費者業務類,去哪一個隊列中獲取消息-->
    <!--配置監聽器管理器
       配置的都是基於topic類型的消息監聽    -->
    <jms:listener-container destination-type="topic" connection-factory="connectionFactory">
        <jms:listener destination="test-spring-topic" ref="activeMqTopicConsumer"/>
    </jms:listener-container>

</beans>

web.xml配置監聽器

   <!-- 監聽器監聽其餘的spring配置文件 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext-jms.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
</web-app>

測試

@Component
public class ActiveMqConsumer implements MessageListener{


    public void onMessage(Message message) {
        //把消息類型轉換成字符串類型消息
        TextMessage textMessage = (TextMessage) message;
        try {
            //輸出消息
            System.out.println("Queue: "+textMessage.getText());
        } catch (JMSException e) {
            e.printStackTrace();
        }
    }
}
@Component
public class ActiveMqTopicConsumer implements MessageListener {

    public void onMessage(Message message) {
        //把消息類型轉換成字符串類型消息
        TextMessage textMessage = (TextMessage) message;
        try {
            //輸出消息
            System.out.println("Topic: "+textMessage.getText());
        } catch (JMSException e) {
            e.printStackTrace();
        }
    }
}

改造郵件發送

引入座標

  <!--activeMq-->
        <dependency>
            <groupId>org.apache.activemq</groupId>
            <artifactId>activemq-all</artifactId>
            <version>${activemq.version}</version>
        </dependency>
        <dependency>
            <groupId>javax.jms</groupId>
            <artifactId>javax.jms-api</artifactId>
            <version>2.0.1</version>
        </dependency>

      <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jms</artifactId>
      <version>${spring.version}</version>
      </dependency>

編寫配置

哪一個發郵件在哪編寫配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:amq="http://activemq.apache.org/schema/core"
       xmlns:jms="http://www.springframework.org/schema/jms"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/jms
        http://www.springframework.org/schema/jms/spring-jms.xsd
        http://activemq.apache.org/schema/core
        http://activemq.apache.org/schema/core/activemq-core.xsd">

   <!-- <context:component-scan base-package="cn.jia"></context:component-scan>-->

    <!--
        spring和activeMq整合:經過整合JmsTemplate對象進行消息發送
    -->
    <!--1.鏈接工廠-->
    <bean id="activeMQConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
        <property name="brokerURL" value="tcp://127.0.0.1:61616"></property>
    </bean>
    <!--2.spring管理鏈接工廠-->
    <bean id="connectionFactory"  class="org.springframework.jms.connection.CachingConnectionFactory">
        <property name="targetConnectionFactory" ref="activeMQConnectionFactory"></property>
    </bean>
    <!--3.指定目的地址:queue或者topic-->
    <bean id="queue" class="org.apache.activemq.command.ActiveMQQueue">
        <!--value:表示在activeMQ中建立的列表名稱-->
        <constructor-arg value="email-queue"></constructor-arg>
    </bean>
    <!--4.經過鏈接工廠建立jmstemplate-->
    <bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
        <property name="connectionFactory" ref="connectionFactory"></property>
    </bean>

</beans>

service實現類

 @Autowired
    private Destination queue; //點對點消息模型

    @Autowired
    private JmsTemplate jmsTemplate;

    public void save(User user) {
        String pwd = user.getPassword();
        //一、保存用戶
        user.setId(UUID.randomUUID().toString());
        user.setPassword(Encrypt.md5(user.getPassword(),user.getEmail()));
        userDao.save(user);

        //二、給用戶發送郵件
        jmsTemplate.send(queue, new MessageCreator() {
            @Override
            public Message createMessage(Session session) throws JMSException {
                MapMessage mapMessage = session.createMapMessage();
                mapMessage.setStringProperty("to",user.getEmail());
                mapMessage.setStringProperty("subject","xxx郵件");
                mapMessage.setStringProperty("content","歡迎您加入xxx有限公司!您的帳號爲:"+user.getEmail()+",初始密碼是:"+pwd);
                return mapMessage;
            }
        });

    /*try {
    MailUtil.sendMsg(user.getEmail(),"xxx郵件","歡迎您加入xxx有限公司!您的帳號爲:"+user.getEmail()+",初始密碼是:"+pwd);
    } catch (Exception e) {
    e.printStackTrace();
     }*/

新建消費者模塊

引入座標(父工程已有)

依賴common裏的發送郵件的工具類

配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:amq="http://activemq.apache.org/schema/core"
       xmlns:jms="http://www.springframework.org/schema/jms"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/jms
        http://www.springframework.org/schema/jms/spring-jms.xsd
        http://activemq.apache.org/schema/core
        http://activemq.apache.org/schema/core/activemq-core.xsd">

    <context:component-scan base-package="cn.jia"></context:component-scan>

    <!--
        spring和activeMq整合:經過整合JmsTemplate對象進行消息發送
    -->
    <!--1.鏈接工廠-->
    <bean id="activeMQConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
        <property name="brokerURL" value="tcp://127.0.0.1:61616"></property>
    </bean>
    <!--2.spring管理鏈接工廠-->
    <bean id="connectionFactory"  class="org.springframework.jms.connection.CachingConnectionFactory">
        <property name="targetConnectionFactory" ref="activeMQConnectionFactory"></property>
    </bean>

    <!--告知消費者業務類,去哪一個隊列中獲取消息-->
    <!--配置監聽器管理器
       配置的都是基於queue類型的消息監聽    -->
    <jms:listener-container destination-type="queue" connection-factory="connectionFactory">
        <jms:listener destination="email-queue" ref="emailListener"/>
    </jms:listener-container>



</beans>

web.xml配置監聽器

    <!-- 監聽器監聽其餘的spring配置文件 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring/applicationContext-jms.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
</web-app>

emailListener

@Component
public class EmailListener implements MessageListener{
    //參數:隊列中的消息對象
    public void onMessage(Message message) {
        try {
            //一、獲取消息數據
            MapMessage mapMessage = (MapMessage) message;
            String to = mapMessage.getStringProperty("to");
            String subject = mapMessage.getStringProperty("subject");
            String content = mapMessage.getStringProperty("content");
            //二、發送郵件
            MailUtil.sendMsg(to,subject,content);

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

    }
}
相關文章
相關標籤/搜索