java 邮件解析

288 阅读2分钟

最近用到了邮件拉取后进行解析,代码调试完后部署到测试环境服务器一切都跑的正常,窃窃自喜,嘿嘿

1650425953(1).jpg

但是..............

邮件解析服务跑一段时间就歇逼了,进入测试服务器查看,发现服务进程存在,但是不再进行邮件解析

1650426080(1).jpg

这难不倒我聪明的小脑瓜

ps -ef | grep java
jstack pid

一顿操作猛如虎,发现线程阻塞在了Stock的读取上,再一段操作猛如虎(百度),发现邮件读取要设置读取的超时时间,如果不设置超时时间,当得不到邮件服务器的响应时,会一直堵在在stock读取

Properties props = new Properties();

// protocol为你使用的邮件协议,我这边使用的是imaps
String key="mail."+protocol+".timeout";
props.put(key,readTimeOut);
session = Session.getDefaultInstance(props);

这么正常跑了一天,又歇逼了,发现出现Folder关闭的异常,但是我明明加了定时任务,通过不断调用Folder的isOpen()方法去维护和邮件服务器的链接,进到源码里面发现每次调用getFloder()方法会返回不同的Folder对象,也就是说我再帮另外一个Floder包活,赶紧偷偷改了.........

 /**
  * Return the Folder object corresponding to the given name. Note
  * that a Folder object is returned even if the named folder does
  * not physically exist on the Store. The <code>exists()</code> 
  * method on the folder object indicates whether this folder really
  * exists. <p>
  *
  * Folder objects are not cached by the Store, so invoking this
  * method on the same name multiple times will return that many
  * distinct Folder objects.
  *
  * @param name    The name of the Folder. In some Stores, name can
  *          be an absolute path if it starts with the
  *          hierarchy delimiter. Else it is interpreted
  *          relative to the 'root' of this namespace.
  * @return       Folder object
  * @exception     IllegalStateException if this Store is not connected.
  * @exception     MessagingException for other failures
  * @see      Folder#exists
  * @see      Folder#create
  */
 public abstract Folder getFolder(String name)
throws MessagingException;

然后又给Floder加了监听,每当监听到关闭事件时,进行重开

/**
 * 给Folder加关闭监听,监听到关闭进行重连
 * @param folder folder
 */
private void addFolderListener(Folder folder){
    try {
        assert folder!=null;

        folder.addConnectionListener(new ConnectionAdapter() {
            @Override
            public void closed(ConnectionEvent e) {
                LOGGER.info("监听到Folder关闭事件,进行重开");
                try {
                    folder.open(Folder.READ_ONLY);
                } catch (MessagingException e1) {
                    LOGGER.info("Folder reOpen Exception",e);
                }
            }
        });
    } catch (Exception e) {
        LOGGER.error("Folder添加监听出现异常",e);
    }
}