Issue
following situation. I have a Spring-Boot Application which handles two main features.
- Reading asynchronously E-Mail from Server via IMAPS. (See below for configuration)
- Providing an API for generating and reading order (this is my business object)
The Problem is curious. If I start my Application without connection to IMAP and reading E-Mails I'm able to make any request to my API. But in the case of starting the E-mail Connection and reading E-Mails I'm not able to make any request to my API.
I receive always following error:
Error: connect ECONNREFUSED 127.0.0.1:8081
Can anyone help me and give me an advise how to handle this?
// Email Connection
Store store = null;
var props = new Properties();
props.setProperty("mail.store.protocol", mailProperties.getProtocol());
try {
var session = Session.getInstance(props, null);
store = session.getStore();
store.connect(
mailProperties.getHost(),
mailProperties.getUsername(),
decodeAsString(mailProperties.getPassword())
);
var inbox = store.getFolder("INBOX");
inbox.open(Folder.READ_WRITE);
waitForNewMessages(inbox);
...
inbox.addMessageCountListener(new MessageCountAdapter() {
@Override
@SneakyThrows
public void messagesAdded(MessageCountEvent ev) {
for (Message message : ev.getMessages()) {
log.info("Message received subject={}, from={}", message.getSubject(), message.getFrom());
emailMessageHandler.handle(message);
}
}
});
...
private void waitForNewMessages(Folder inbox) throws MessagingException {
while (inbox.isOpen()) {
//every 25 minutes poke the server with a inbox.getMessageCount() to keep the connection active/open
var scheduler = Executors.newScheduledThreadPool(1);
final Runnable pokeInbox = () -> {
try {
inbox.getMessageCount();
} catch (MessagingException ex) {
//nothing doin'
}
};
scheduler.schedule(pokeInbox, 25, TimeUnit.MINUTES);
((IMAPFolder) inbox).idle();
}
}
Solution
After researching the whole www, I found the following solution IdleManager
.
IdleManager uses an ExecutorService for listening for all events from the SMTP-Server and it doesn't block the Web-Application for other incoming request.
For getting in touch and more information you can see the following documentation. IdleManager
Answered By - ramazan86