io.pythagoras.messagebus.adapter.awssnssqs.AwsSnsSqsAdapter Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of adapter-sqs-sns Show documentation
Show all versions of adapter-sqs-sns Show documentation
Pythagoras SQS/SNS Adapter for Message Bus
package io.pythagoras.messagebus.adapter.awssnssqs;
import com.amazonaws.services.sns.AmazonSNS;
import com.amazonaws.services.sns.model.*;
import com.amazonaws.services.sqs.AmazonSQS;
import com.amazonaws.services.sqs.model.DeleteQueueRequest;
import io.pythagoras.messagebus.adapter.awssnssqs.config.Properties;
import io.pythagoras.messagebus.adapter.awssnssqs.exceptions.SNSNotExistsException;
import io.pythagoras.messagebus.annotations.MessageBusAdapter;
import io.pythagoras.messagebus.core.*;
import io.pythagoras.messagebus.core.config.MessageBusProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.beans.factory.annotation.Value;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@MessageBusAdapter
public class AwsSnsSqsAdapter implements IMessageBusAdapter {
private static final Logger logger = LoggerFactory.getLogger(AwsSnsSqsAdapter.class);
private AmazonSQS sqs;
private SQSClientProvider sqsClientProvider;
private AmazonSNS sns;
private SNSRegistry snsRegistry;
private Properties properties;
private String appName;
private String queueUrl;
private Map codeToDedicatedQueuePerServiceUrl;
private Map codeToDedicatedQueuePerInstanceUrl;
private MessageBusProperties messageBusProperties;
private List sqsConsumers = new ArrayList<>();
@Autowired
public void setSQS(SQSClientProvider provider) {
this.sqsClientProvider = provider;
this.sqs = provider.getSyncClient();
}
@Autowired
public void setSNS(SNSClientProvider provider) {
this.sns = provider.getSyncClient();
}
@Autowired
public void setSnsRegistry(SNSRegistry snsRegistry) {
this.snsRegistry = snsRegistry;
}
@Autowired
public void setProperties(Properties properties) {
this.properties = properties;
}
@Autowired
public void setMessageBusProperties(MessageBusProperties msgBusProps) {
this.messageBusProperties = msgBusProps;
}
@Required
@Value("${spring.application.name}")
public void setAppName(String appName) {
this.appName = appName;
}
@Override
public void initialize(List messageCodes, List handlerCodes, Map>> messageCodesAndMessageContracts) throws MessageBusInitializationException {
if (messageBusProperties.isEnabled()) {
Initializer initializer = new Initializer(snsRegistry, properties, sns, sqs);
initializer.initialize(messageCodes, handlerCodes, messageCodesAndMessageContracts, appName);
this.queueUrl = initializer.getQueueUrl();
this.codeToDedicatedQueuePerServiceUrl = initializer.getCodeToDedicatedQueuePerServiceUrl();
this.codeToDedicatedQueuePerInstanceUrl = initializer.getCodeToDedicatedQueuePerInstanceUrl();
}
}
@Override
public void sendMessage(IBusMessage message) throws MessageSendingException {
if (!messageBusProperties.isEnabled()) {
throw new MessageSendingException("Message Bus is Disabled. Unable to send messages.");
}
// Get the exchange
String exchange;
try {
exchange = this.snsRegistry.getARN(message.getCode());
} catch (SNSNotExistsException e) {
throw new MessageSendingException("Unable to locate exchange. ", e);
}
// Create the request
PublishRequest request = new PublishRequest();
request.setTopicArn(exchange);
request.setMessage(message.getPayload());
Map attrs = new HashMap<>();
attrs.put("MessageCode", createAttributeValue(message.getCode()));
attrs.put("MessageVersion", createAttributeValue(message.getVersion().toString()));
request.setMessageAttributes(attrs);
// Send the message
try {
this.sns.publish(request);
} catch (InvalidParameterException | InvalidParameterValueException | InternalErrorException | NotFoundException | EndpointDisabledException | PlatformApplicationDisabledException | AuthorizationErrorException e) {
throw new MessageSendingException("Unable to send message.", e);
}
}
public List getConsumers() {
return sqsConsumers;
}
private MessageAttributeValue createAttributeValue(String str) {
MessageAttributeValue mav = new MessageAttributeValue();
mav.setDataType("String");
mav.setStringValue(str);
return mav;
}
@Override
public void registerMessageBusService(IMessageBus messageBus) {
if (messageBusProperties.isEnabled() && messageBusProperties.isReceiveEnabled()) {
if (this.queueUrl == null && this.codeToDedicatedQueuePerServiceUrl.isEmpty() && this.codeToDedicatedQueuePerInstanceUrl.isEmpty()) {
throw new BaseRunTimeException("Adapter must be initialized prior to registration of message handler.");
}
if (this.queueUrl != null) {
SqsConsumer sqsConsumer = new SqsConsumer(this.sqsClientProvider, messageBus, this.queueUrl);
sqsConsumer.setParallelReceivers(this.properties.getParallelReceivers());
this.sqsConsumers.add(sqsConsumer);
}
for (Map.Entry entry : codeToDedicatedQueuePerServiceUrl.entrySet()) {
SqsConsumer sqsConsumer = new SqsConsumer(this.sqsClientProvider, messageBus, entry.getValue());
sqsConsumer.setParallelReceivers(this.properties.getParallelReceivers());
this.sqsConsumers.add(sqsConsumer);
}
for (Map.Entry entry : codeToDedicatedQueuePerInstanceUrl.entrySet()) {
SqsConsumer sqsConsumer = new SqsConsumer(this.sqsClientProvider, messageBus, entry.getValue());
sqsConsumer.setParallelReceivers(this.properties.getParallelReceivers());
this.sqsConsumers.add(sqsConsumer);
}
}
}
@Override
public void stop() throws MessageBusStateException {
for (SqsConsumer sqsConsumer : sqsConsumers)
if (sqsConsumer != null) {
sqsConsumer.stop();
}
}
@Override
public void start() throws MessageBusStateException {
for (SqsConsumer sqsConsumer : sqsConsumers) {
if (sqsConsumer == null) {
throw new MessageBusStateException("Consumer is null.");
}
sqsConsumer.start();
}
}
@Override
public void cleanResources() throws MessageBusStateException {
logger.info("Starting removal of dedicated queues per instance.");
try {
List queueUrls = new ArrayList<>();
for (Map.Entry entry : codeToDedicatedQueuePerInstanceUrl.entrySet()) {
queueUrls.add(entry.getValue());
}
logger.info(String.format("Number of queues to be deleted: %s.", queueUrls.size()));
queueUrls.forEach(url -> logger.info(String.format("Queue url for removal: %s.", url)));
for (String queueUrl : queueUrls) {
logger.info(String.format("Deleting queue: %s.", queueUrl));
sqs.deleteQueue(new DeleteQueueRequest(queueUrl));
}
logger.info("Removal of dedicated queues per instance completed without exceptions.");
} catch (RuntimeException e) {
logger.info("Removal of dedicated queues per instance completed with exception.", e);
}
}
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy