1.搭建一个dubbo + zookeeper 的环境   dubbo + zookeeper环境搭建

2.新建两个工程 

    2.1简单的 api接口工程 email-api

    

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

  <modelVersion>4.0.0</modelVersion>

  <groupId>com.wl.common.email.api</groupId>
  <artifactId>email-api</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>email-api</name>
  <url>http://maven.apache.org</url>


  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

  </properties>

  <dependencies>

  </dependencies>
  <!-- 打包源码插件-->
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-source-plugin</artifactId>
        <executions>
          <execution>
            <id>attach-sources</id>
            <goals>
              <goal>jar</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>

  </build>

</project>

  2.2 实现上面接口的email-service工程  pom.xml 如下

  

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.wl.microservice.email</groupId>
  <artifactId>email-service</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>email-service</name>
  <url>http://maven.apache.org</url>


  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <email-version>1.0-SNAPSHOT</email-version>
    <MainClass>com.wl.microservice.email.EmailApplication</MainClass>

    <spring-boot-version>1.5.7.RELEASE</spring-boot-version>

    <mysql-connector-java-version>6.0.6</mysql-connector-java-version>
    <hibernate-core-version>5.2.10.Final</hibernate-core-version>
    <spring-cloud-starter-config-version>1.2.2.RELEASE</spring-cloud-starter-config-version>

    <dubbo-version>2.6.0</dubbo-version>
    <resteasy-netty-version>3.5.0.Final</resteasy-netty-version>
    <zookeeper-version>3.4.10</zookeeper-version>
    <slf4j-api-version>1.7.5</slf4j-api-version>
    <commons-lang3-version>3.6</commons-lang3-version>
    <!-- groovy -->
    <groovy-all-version>2.4.5</groovy-all-version>

    <!-- 测试 -->
    <junit.version>4.12</junit.version>
    <groovy-all-version>2.4.5</groovy-all-version>
    <spock-core-version>1.1-groovy-2.4</spock-core-version>
  </properties>

  <dependencies>
    <!-- 接口 -->
    <dependency>
      <groupId>com.wl.common.email.api</groupId>
      <artifactId>email-api</artifactId>
      <version>${email-version}</version>
    </dependency>

    <!-- spring boot -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
      <version>${spring-boot-version}</version>
      <exclusions>
        <exclusion>
          <groupId>org.slf4j</groupId>
          <artifactId>slf4j-api</artifactId>
        </exclusion>
      </exclusions>
    </dependency>

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


    <!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-config -->
    <!-- 依赖 spring-web -->
    <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter-config</artifactId>
      <version>${spring-cloud-starter-config-version}</version>
      <exclusions>
        <exclusion>
          <groupId>com.fasterxml.jackson.core</groupId>
          <artifactId>jackson-databind</artifactId>
        </exclusion>
        <exclusion>
          <groupId>org.springframework.boot</groupId>
          <artifactId>*</artifactId>
        </exclusion>
        <exclusion>
          <groupId>org.springframework</groupId>
          <artifactId>spring-web</artifactId>
        </exclusion>
        <exclusion>
          <groupId>com.fasterxml.jackson.core</groupId>
          <artifactId>jackson-annotations</artifactId>
        </exclusion>
      </exclusions>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-mail -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-mail</artifactId>
      <version>${spring-boot-version}</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/com.alibaba/dubbo -->
    <!-- dubbo 依赖 spring-context 和 spring-beans spring-web-->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>dubbo</artifactId>
      <version>${dubbo-version}</version>
      <exclusions>
        <exclusion>
          <groupId>org.springframework</groupId>
          <artifactId>spring-beans</artifactId>
        </exclusion>
        <exclusion>
          <groupId>org.springframework</groupId>
          <artifactId>spring-context</artifactId>
        </exclusion>
        <exclusion>
          <groupId>org.springframework</groupId>
          <artifactId>spring-web</artifactId>
        </exclusion>
      </exclusions>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-lang3</artifactId>
      <version>${commons-lang3-version}</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.jboss.resteasy/resteasy-netty -->
    <dependency>
      <groupId>org.jboss.resteasy</groupId>
      <artifactId>resteasy-netty</artifactId>
      <version>${resteasy-netty-version}</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.apache.zookeeper/zookeeper -->
    <dependency>
      <groupId>org.apache.zookeeper</groupId>
      <artifactId>zookeeper</artifactId>
      <version>${zookeeper-version}</version>
      <exclusions>
        <exclusion>
          <artifactId>log4j</artifactId>
          <groupId>log4j</groupId>
        </exclusion>
        <exclusion>
          <groupId>org.slf4j</groupId>
          <artifactId>slf4j-api</artifactId>
        </exclusion>
        <exclusion>
          <groupId>org.slf4j</groupId>
          <artifactId>slf4j-log4j12</artifactId>
        </exclusion>
      </exclusions>
    </dependency>

    <!---日志 -->
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>${slf4j-api-version}</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/com.github.sgroschupf/zkclient -->
    <dependency>
      <groupId>com.github.sgroschupf</groupId>
      <artifactId>zkclient</artifactId>
      <version>0.1</version>

      <exclusions>
        <exclusion>
          <groupId>org.apache.zookeeper</groupId>
          <artifactId>zookeeper</artifactId>
        </exclusion>
      </exclusions>
    </dependency>

    <!-- groovy -->
    <!-- https://mvnrepository.com/artifact/org.codehaus.groovy/groovy-all -->
    <dependency>
      <groupId>org.codehaus.groovy</groupId>
      <artifactId>groovy-all</artifactId>
      <version>${groovy-all-version}</version>
    </dependency>

    <!-- 测试依赖  scope test   不会打进jar包 -->

    <!-- https://mvnrepository.com/artifact/junit/junit -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>${junit.version}</version>
      <scope>test</scope>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.spockframework/spock-core -->
    <dependency>
      <groupId>org.spockframework</groupId>
      <artifactId>spock-core</artifactId>
      <version>${spock-core-version}</version>
      <scope>test</scope>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-test -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <version>${spring-boot-version}</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-autoconfigure</artifactId>
      <version>${spring-boot-version}</version>
    </dependency>


  </dependencies>

  <!-- Package as an executable jar -->
  <build>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
        <version>${spring-boot-version}</version>
        <configuration>
          <mainClass>${MainClass}</mainClass>
          <layout>JAR</layout>
        </configuration>
        <!-- repackage  生成两个 jar.original -->
        <executions>
          <execution>
            <goals>
              <goal>repackage</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
      <!-- 指定maven 打包java 版本 -->
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.1</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
    </plugins>
    <!-- maven  编译打包resource 和 java 目录下所有文件  maven默认资源路径是resources -->
    <resources>
      <resource>
        <directory>src/main/resource</directory>
        <includes>
          <include>**/*.*</include>
          <include>*.*</include>
        </includes>
      </resource>
      <resource>
        <directory>src/main/java</directory>
        <includes>
          <include>**/*.*</include>
          <include>*.*</include>
        </includes>
      </resource>
    </resources>
  </build>

</project>

3.配置

    3.1  application.properties

    

#banner
banner.charset=UTF-8
banner.location=classpath:banner.txt
#logger
logging.config=classpath:logger/logback-boot.xml

# http port
#server.port=9001
#dubbo
dubbo.port=20211
#dubbo.host=172.20.55.141
dubbo.host=127.0.0.1
#dubbo.host=192.168.1.112
#zookeeper
env.host.zookeeper=192.168.46.128
zookeeper.address=zookeeper://${env.host.zookeeper}:2181?timeout=20000

#spring.main.web-environment=false

    3.2 application.yml(邮件服务器配置)

    

spring:
  mail:
    host: smtp.qq.com
    port: 587
    username: ***@qq.com
    password: ****
    properties:
        mail:
            smtp:
                auth: true
                timeout: 3000
                connectiontimeout: 5000
                writetimeout: 3000

开启邮件服务 在 设置-账号 如下图

3.3 dubbo 配置

参考  http://dubbo.apache.org/#!/docs/user/references/xml/introduction.md?lang=zh-cn

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://code.alibabatech.com/schema/dubbo
       http://code.alibabatech.com/schema/dubbo/dubbo.xsd">

    <!--半自动化,使用annotation来注解-->
    <dubbo:application name="email-service"/>
    <!-- 使用zookeeper广播注册中心暴露服务地址 -->
    <dubbo:registry protocol="zookeeper" address="${zookeeper.address}"/>
    <!-- 扫描注解包路径,多个包用逗号分隔,不填pacakge表示扫描当前ApplicationContext中所有的类 -->
    <dubbo:annotation package="com.wl.microservice.email"/>
    <!--这里可以声明多种协议,rest的协议应该使用内嵌的tomcat-->
    <dubbo:protocol name="dubbo" port="${dubbo.port}" host="${dubbo.host}"/>
    <dubbo:consumer check="false" version="1.0.0" retries="0"/>
    <dubbo:provider version="1.0.0" retries="0"/>
    <dubbo:monitor protocol="registry"/>
</beans>

3.4 日志

<?xml version="1.0" encoding="UTF-8"?>

    <configuration>
        <!-- %m输出的信息,%p日志级别,%t线程名,%d日期,%c类的全名,%i索引【从数字0开始递增】,,, -->
        <!-- appender是configuration的子节点,是负责写日志的组件。 -->
        <!-- ConsoleAppender:把日志输出到控制台 -->
        <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
            <encoder>
                <pattern>%d %p (%file:%line\)- %m%n</pattern>
                <!-- 控制台也要使用UTF-8,不要使用GBK,否则会中文乱码 -->
                <charset>UTF-8</charset>
            </encoder>
        </appender>
        <!-- RollingFileAppender:滚动记录文件,先将日志记录到指定文件,当符合某个条件时,将日志记录到其他文件 -->
        <!-- 以下的大概意思是:1.先按日期存日志,日期变了,将前一天的日志文件名重命名为XXX%日期%索引,新的日志仍然是sys.log -->
        <!--             2.如果日期没有发生变化,但是当前日志的文件大小超过1KB时,对当前日志进行分割 重命名-->
        <appender name="syslog"
                  class="ch.qos.logback.core.rolling.RollingFileAppender">
            <File>log/email/email.log</File>
            <!-- rollingPolicy:当发生滚动时,决定 RollingFileAppender 的行为,涉及文件移动和重命名。 -->
            <!-- TimeBasedRollingPolicy: 最常用的滚动策略,它根据时间来制定滚动策略,既负责滚动也负责出发滚动 -->
            <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
                <!-- 活动文件的名字会根据fileNamePattern的值,每隔一段时间改变一次 -->
                <!-- 文件名:log/sys.2017-12-05.0.log -->
                <fileNamePattern>log/email/email.%d.%i.log</fileNamePattern>
                <!-- 每产生一个日志文件,该日志文件的保存期限为30天 -->
                <maxHistory>30</maxHistory>
                <timeBasedFileNamingAndTriggeringPolicy  class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                    <!-- maxFileSize:这是活动文件的大小,默认值是10MB,本篇设置为1KB,只是为了演示 -->
                    <maxFileSize>100MB</maxFileSize>
                </timeBasedFileNamingAndTriggeringPolicy>
            </rollingPolicy>
            <encoder>
                <!-- pattern节点,用来设置日志的输入格式 -->
                <pattern>
                    %d %p (%file:%line\)- %m%n
                </pattern>
                <!-- 记录日志的编码 -->
                <charset>UTF-8</charset> <!-- 此处设置字符集 -->
            </encoder>
        </appender>
        <!-- 控制台输出日志级别 -->
        <root level="info">
            <appender-ref ref="syslog" />
        </root>
        <root level="info">
            <appender-ref ref="STDOUT" />
        </root>
        <!-- 指定项目中某个包,当有日志操作行为时的日志记录级别 -->
        <!-- com.appley为根包,也就是只要是发生在这个根包下面的所有日志操作行为的权限都是DEBUG -->
        <!-- 级别依次为【从高到低】:FATAL > ERROR > WARN > INFO > DEBUG > TRACE  -->
        <logger name="com.wl.blog.common" level="DEBUG">
            <appender-ref ref="syslog" />
        </logger>
    <logger name="org.apache.http" level="DEBUG" >
        <appender-ref ref="syslog"/>
    </logger>
    </configuration>

4.代码

  4.1加载dubbo配置文件的配置类

  

package com.wl.microservice.email.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;

/**
 * Created by wl on 2018/2/27.
 */
@Configuration
@ImportResource(locations = "classpath:dubbo/dubbo.xml")
public class DubboConfig {
}

4.2 api 接口

package com.wl.common.email.api.interfaces;

import java.util.Map;

/**
 * Created by wl on 2018/2/24.
 */
public interface ISendEmailsMicroService {


    /**
     *
     * @param emailTo
     *          收件人
     * @param emailCC
     *          抄送
     * @param emailBCC
     *          秘密抄送
     * @param text
     *          内容
     * @param subject
     *          主题
     */
    void sendText(String[] emailTo, String[] emailCC, String[] emailBCC, String text, String subject) throws Exception;


    /**
     *
     * @param emailTo
     *          收件人
     * @param emailCC
     *          抄送
     * @param emailBCC
     *          秘密抄送
     * @param html
     *          内容
     * @param contentMap
     *          contentId  url 键值对
     * @param subject
     *          主题
     */
    void sendHTML(String[] emailTo, String[] emailCC, String[] emailBCC, String html, Map<String,String> contentMap, String subject) throws Exception;


    /**
     *
     * @param emailTo
     *          收件人
     * @param emailCC
     *          抄送
     * @param emailBCC
     *          秘密抄送
     * @param text
     *          内容
     * @param attachNames
     *          附件名称
     * @param attachUrls
     *          附件url连接
     * @param subject
     *          主题
     */
    void sendAttachment(String[] emailTo, String[] emailCC, String[] emailBCC, String text, String[] attachNames,String[] attachUrls, String subject) throws Exception;


}

4.3 接口实现(注意Service 注解)

package com.wl.microservice.email.dubbo;

import com.alibaba.dubbo.config.annotation.Service;
import com.wl.common.email.api.interfaces.ISendEmailsMicroService;
import com.wl.microservice.email.service.SendEmailService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Map;

/**
 * Created by wl on 2018/2/26.
 */
@Service(protocol = "dubbo")
//    @org.springframework.stereotype.Service
public class SendEmailMicroService implements ISendEmailsMicroService {

    private static final Logger logger = LoggerFactory.getLogger(SendEmailMicroService.class);

    private SendEmailService sendEmailService;

    @Autowired
    public SendEmailMicroService(SendEmailService sendEmailService) throws Exception {
        System.out.println("=======================================================");
        this.sendEmailService = sendEmailService;

    }

    /**
     * @param emailTo  收件人
     * @param emailCC  抄送
     * @param emailBCC 秘密抄送
     * @param text     内容
     * @param subject  主题
     */
    public void sendText(String[] emailTo, String[] emailCC, String[] emailBCC, String text, String subject) {
        sendEmailService.sendText(emailTo,emailCC,emailBCC,text,subject);
    }


    /**
     * @param emailTo  收件人
     * @param emailCC  抄送
     * @param emailBCC 秘密抄送
     * @param html     内容
     * @param contentMap 键值对
     * @param subject  主题
     */
    @Override
    public void sendHTML(String[] emailTo, String[] emailCC, String[] emailBCC, String html, Map<String,String> contentMap, String subject) throws Exception{
        logger.info("发送html邮件 emailTo:{},emailCC:{},emailBCC:{}",emailTo,emailCC,emailBCC);
        sendEmailService.sendHTML(emailTo,emailCC,emailBCC,html,contentMap,subject);
    }

    /**
     * @param emailTo  收件人
     * @param emailCC  抄送
     * @param emailBCC 秘密抄送
     * @param text     内容
     * @param attachNames    附件名
     * @param attachUrl      附件路径
     * @param subject  主题
     */
    @Override
    public void sendAttachment(String[] emailTo, String[] emailCC, String[] emailBCC, String text, String[] attachNames,String[] attachUrl ,String subject) throws Exception {
        logger.info("发送带附件邮件 emailTo:{},emailCC:{},emailBCC:{}",emailTo,emailCC,emailBCC);
        sendEmailService.sendAttachment(emailTo,emailCC,emailBCC,text,attachNames,attachUrl,subject);
    }



}

4.4 service

package com.wl.microservice.email.service;

import com.wl.microservice.email.thread.SendMailThread;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.core.io.UrlResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.Map;
import java.util.Set;

/**
 * Created by wl on 2018/4/4.
 */
@Service
public class SendEmailService {

    private JavaMailSender mailSender;

//    private MailProperties mailProperties;

    private SimpleMailMessage templateMessage;

    @Autowired
    public SendEmailService(JavaMailSender mailSender,MailProperties mailProperties) throws Exception {
        System.out.println("=======================================================");
        this.mailSender = mailSender;
        this.templateMessage = new SimpleMailMessage();
        this.templateMessage.setFrom(mailProperties.getUsername());

    }


    /**
     * @param emailTo  收件人
     * @param emailCC  抄送
     * @param emailBCC 秘密抄送
     * @param text     内容
     * @param subject  主题
     */
    public void sendText(String[] emailTo, String[] emailCC, String[] emailBCC, String text, String subject) {
        SimpleMailMessage message = new SimpleMailMessage(this.templateMessage);
        message.setTo(emailTo);
        if(emailCC != null && emailCC.length > 0){
            message.setCc(emailCC);
        }
        if(emailBCC != null && emailBCC.length > 0){
            message.setBcc(emailBCC);
        }
        message.setSubject(subject);
        message.setSentDate(new Date());
        message.setText(text);
//        mailSender.send(message);
        SendMailThread.sendEmail(mailSender,message);
    }


    /**
     * @param emailTo  收件人
     * @param emailCC  抄送
     * @param emailBCC 秘密抄送
     * @param html     内容
     * @param contentMap 键值对
     * @param subject  主题
     */
    public void sendHTML(String[] emailTo, String[] emailCC, String[] emailBCC, String html, Map<String,String> contentMap, String subject) throws Exception{
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper helper = genMimeHelper(emailTo,emailCC,emailBCC,mimeMessage);

        helper.setText(html,true);
        if(contentMap != null && contentMap.size() > 0){
            Set<Map.Entry<String,String>> entrySet = contentMap.entrySet();
            for(Map.Entry<String,String> entry : entrySet){
//                helper.addInline(entry.getKey(),new File(entry.getValue()));    File
//                helper.addInline(entry.getKey(),new ByteArrayDataSource(IOUtils.toByteArray(new URL(entry.getValue())),MimeTypeUtils.ALL_VALUE));   ByteArrayDataSource  UrlDataSource
                helper.addInline(entry.getKey(),new UrlResource(entry.getValue()));                                //UrlResource
            }
        }
        helper.setSubject(subject);
//        mailSender.send(mimeMessage);
        SendMailThread.sendEmail(mailSender,mimeMessage);
    }

    /**
     * @param emailTo  收件人
     * @param emailCC  抄送
     * @param emailBCC 秘密抄送
     * @param text     内容
     * @param attachNames    附件名
     * @param attachUrl      附件路径
     * @param subject  主题
     */
    public void sendAttachment(String[] emailTo, String[] emailCC, String[] emailBCC, String text, String[] attachNames,String[] attachUrl ,String subject) throws Exception {
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper helper = genMimeHelper(emailTo,emailCC,emailBCC,mimeMessage);
        helper.setText(text,true);
        helper.setSubject(subject);
        if(attachNames != null && attachUrl != null && attachNames.length > 0){
            for(int i=0;i<attachNames.length && i<attachUrl.length ;i++){
//                helper.addAttachment(file.getName(),file);    File
                String attachName = attachNames[i];
                String url = attachUrl[i];
//                helper.addAttachment(attachName,new ByteArrayDataSource(IOUtils.toByteArray((new URI(url))), MimeTypeUtils.ALL_VALUE));   //DataSource
                helper.addAttachment(attachName,new UrlResource(url));
            }
        }

//        mailSender.send(mimeMessage);
        SendMailThread.sendEmail(mailSender,mimeMessage);
    }




    private MimeMessageHelper genMimeHelper(String[] emailTo, String[] emailCC, String[]emailBCC, MimeMessage mimeMessage) throws MessagingException {

        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true, "UTF-8");    //带附件

        helper.setTo(emailTo);
        if(emailCC != null && emailCC.length > 0){
            helper.setCc(emailCC);
        }
        if(emailBCC != null && emailBCC.length > 0){
            helper.setBcc(emailBCC);
        }
        helper.setFrom(this.templateMessage.getFrom());
        return helper;
    }


}

4.5 thread 

package com.wl.microservice.email.thread;

import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;

import javax.mail.internet.MimeMessage;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by wl on 2018/3/20.
 */
public class SendMailThread{

    private static final ExecutorService executorService = Executors.newFixedThreadPool(300);

    public static void sendEmail(JavaMailSender mailSender, MimeMessage mailMessage){
        executorService.execute(() -> mailSender.send(mailMessage));
    }


    public static void sendEmail(JavaMailSender mailSender, SimpleMailMessage mailMessage){
        executorService.execute(() -> mailSender.send(mailMessage));
    }

}

4.6 启动类

package com.wl.microservice.email;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;

import java.util.concurrent.CountDownLatch;

/**
 * Created by wl on 2018/2/26.
 */
@SpringBootApplication(exclude = {
        DataSourceAutoConfiguration.class,
        DataSourceTransactionManagerAutoConfiguration.class,
        HibernateJpaAutoConfiguration.class,              //不使用数据库
        }
        ,scanBasePackages = "com.wl"
)
public class EmailApplication {
    private static final Logger logger = LoggerFactory.getLogger(EmailApplication.class);

    public static void main(String[] args) throws InterruptedException {
        SpringApplication app = new SpringApplication(EmailApplication.class);
        app.setWebEnvironment(false);      //不依赖web环境  启动后应用会马上关闭
//        app.setWebApplicationType(WebApplicationType.NONE);
        app.run(args);
        logger.info("=================>>SpringBoot Success" );
//
        new CountDownLatch(1).await();//防止应用关闭
    }
}

5 启动应用 查看dubbo-admin 是否有了该服务

 

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐