Search code examples
javaspring-bootcontainersspring-integration

spring integration to read emails with multiple instances of spring boot application


I run a spring boot application using below configuration to read emails from a given email account. However, this springboot application is containerized and hence we have multiple instances of this application running at a given time.

My question is, Do multiple consumers[app instances] will get same message to process from the email account or it would not be available to other consumers[app instances] if anyone of the consumer reads it? I am trying to avoid duplicate processing of messages.

Configuration xml -


<int-mail:inbound-channel-adapter id="imapAdapter"
                                      store-uri="imaps://abc.com/INBOX"
                                      channel="receiveChannel"
                                      should-delete-messages="false"
                                      should-mark-messages-as-read="true"
                                      java-mail-properties="javaMailProperties"
                                      auto-startup="true">
        <int:poller max-messages-per-poll="1" fixed-rate="600000" />

    </int-mail:inbound-channel-adapter>

    <util:properties id="javaMailProperties">
        <prop key="mail.imap.socketFactory.class">javax.net.ssl.SSLSocketFactory</prop>
        <prop key="mail.imap.socketFactory.fallback">false</prop>
        <prop key="mail.store.protocol">imaps</prop>
        <prop key="mail.debug">false</prop>
        <prop key="mail.smtp.ssl.protocols">TLSv1.2</prop>
    </util:properties>

    <bean id="mailService" class="com.xpressbees.poller.EmailPoller"/>

    <int:service-activator id="serviceActivator" input-channel="receiveChannel" ref="mailService" method="handleMail"/>



Solution

  • The should-mark-messages-as-read="true" is enough for IMAP mail receiver to skip those messages on other instances or for subsequent fetch: NotTerm notSeen = new NotTerm(new FlagTerm(new Flags(Flags.Flag.SEEN), true));.

    Do you observe some other behavior?

    UPDATE

    You also can use a leader election feature from Spring Integration, where only one active instance is going to pull mail box: https://docs.spring.io/spring-integration/docs/current/reference/html/messaging-endpoints.html#leadership-event-handling. Another feature is to use an Idempotent Receiver advice to prevent duplicates: https://docs.spring.io/spring-integration/docs/current/reference/html/messaging-endpoints.html#idempotent-receiver