You can use sqslistener
annotation from SpringCloud framework.
If you are developing application with Spring
and AWS
and you are not using Spring Cloud
, it is good time for you to switch.
Here is a sample code to asynchronously receive message from SQS using sqslistener
annotation. A good thing is you have to almost zero configuration for using this :
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.aws.messaging.listener.SqsMessageDeletionPolicy;
import org.springframework.cloud.aws.messaging.listener.annotation.SqsListener;
import org.springframework.stereotype.Component;
import com.example.my.RecoverableException;
@Component
@Slf4j
public class CustomMessageQueue {
@SqsListener(value = "${build_request_queue.name}", deletionPolicy = SqsMessageDeletionPolicy.ON_SUCCESS)
public void receive(String message) {
try {
// write message processing here
} catch (RecoverableException e) {
// handle errors here for which message from queue should not be deleted
// throwing an exception will make receive method fail and hence message does not get deleted
throw e;
} catch (Exception e) {
// suppress exceptions for which message should be deleted.
}
}
}
The great thing about sqslistener
annotation is its deletionPolicy
. So you can decide when a message from SQS gets deleted.
queue
from to pass to the.createConsumer
method? I use an existing queue, I do not want to create a new queue. – Inscribe