简体   繁体   中英

Spring JavaMailSender - best way to use session

What's the best way to reuse sessions in Spring JavaMailSender?

In a scenario where a consumer reads messages from a queue and trigger emails based on the messages, the emails will be send one after the other. If a new session is created everytime, isn't that an overhead? If JavaMailSender is a singleton bean, does it use the same session always? What's the best solution here?

I saw samples of JNDI sessions being set in to JavaMailSender bean configuration. We don't have support for JNDI, so that's not an option.

If you use the standard JavaMailSender for the MailSendingMessageHandler , so you just reuse the Session !

// Check transport connection first...
if (transport == null || !transport.isConnected()) {
...
try {
    transport = connectTransport();
}

...

Transport transport = getTransport(getSession());
transport.connect(getHost(), getPort(), username, password);
return transport;

...

public synchronized Session getSession() {
    if (this.session == null) {
        this.session = Session.getInstance(this.javaMailProperties);
    }
    return this.session;
}

Not sure from where you heard that a new session is created for each message...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM