GH-344 - Support for event externalization into AWS SNS and SQS.

Additional event externalization implementations for AWS SNS and SQS.

Original pull request: GH-350.
This commit is contained in:
Maciej Walkowiak
2023-10-28 12:23:54 +02:00
committed by Oliver Drotbohm
parent 0ae19fb301
commit d95da874bd
19 changed files with 860 additions and 1 deletions

View File

@@ -42,7 +42,7 @@
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<spring.version>6.1.0-RC1</spring.version> <!-- For Javadoc links only -->
<spring-boot.version>3.2.0-RC1</spring-boot.version>
<spring-cloud-aws-bom.version>3.0.2</spring-cloud-aws-bom.version>
</properties>
<developers>
@@ -407,6 +407,13 @@ limitations under the License.
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>io.awspring.cloud</groupId>
<artifactId>spring-cloud-aws-dependencies</artifactId>
<version>${spring-cloud-aws-bom.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>

View File

@@ -16,6 +16,8 @@
<modules>
<module>spring-modulith-events-amqp</module>
<module>spring-modulith-events-api</module>
<module>spring-modulith-events-aws-sns</module>
<module>spring-modulith-events-aws-sqs</module>
<module>spring-modulith-events-core</module>
<module>spring-modulith-events-jackson</module>
<module>spring-modulith-events-jdbc</module>

View File

@@ -0,0 +1,96 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.modulith</groupId>
<artifactId>spring-modulith-events</artifactId>
<version>1.1.0-SNAPSHOT</version>
</parent>
<name>Spring Modulith - Events - AWS SNS support</name>
<artifactId>spring-modulith-events-aws-sns</artifactId>
<properties>
<module.name>org.springframework.modulith.events.aws.sns</module.name>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.modulith</groupId>
<artifactId>spring-modulith-api</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.modulith</groupId>
<artifactId>spring-modulith-events-core</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>io.awspring.cloud</groupId>
<artifactId>spring-cloud-aws-sns</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<optional>true</optional>
</dependency>
<!-- Test dependencies -->
<dependency>
<groupId>org.springframework.modulith</groupId>
<artifactId>spring-modulith-starter-jdbc</artifactId>
<version>${project.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-json</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-testcontainers</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.awspring.cloud</groupId>
<artifactId>spring-cloud-aws-starter-sns</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.awspring.cloud</groupId>
<artifactId>spring-cloud-aws-starter-sqs</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>localstack</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@@ -0,0 +1,85 @@
/*
* Copyright 2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.modulith.events.aws.sns;
import io.awspring.cloud.sns.core.SnsNotification;
import io.awspring.cloud.sns.core.SnsOperations;
import io.awspring.cloud.sns.core.SnsTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.services.sns.model.InvalidParameterException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.expression.BeanFactoryResolver;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.messaging.MessageDeliveryException;
import org.springframework.modulith.events.EventExternalizationConfiguration;
import org.springframework.modulith.events.config.EventExternalizationAutoConfiguration;
import org.springframework.modulith.events.support.BrokerRouting;
import org.springframework.modulith.events.support.DelegatingEventExternalizer;
/**
* Auto-configuration to set up a {@link DelegatingEventExternalizer} to externalize events to SNS.
*
* @author Maciej Walkowiak
* @since 1.1
*/
@AutoConfiguration
@AutoConfigureAfter(EventExternalizationAutoConfiguration.class)
@ConditionalOnClass(SnsTemplate.class)
@ConditionalOnProperty(name = "spring.modulith.events.externalization.enabled",
havingValue = "true",
matchIfMissing = true)
class SnsEventExternalizerConfiguration {
private static final Logger logger = LoggerFactory.getLogger(SnsEventExternalizerConfiguration.class);
@Bean
DelegatingEventExternalizer snsEventExternalizer(EventExternalizationConfiguration configuration,
SnsOperations operations, BeanFactory factory) {
logger.debug("Registering domain event externalization to SNS…");
var context = new StandardEvaluationContext();
context.setBeanResolver(new BeanFactoryResolver(factory));
return new DelegatingEventExternalizer(configuration, (target, payload) -> {
var routing = BrokerRouting.of(target, context);
var builder = SnsNotification.builder(payload);
var key = routing.getKey(payload);
// when routing key is set, SNS topic must be a FIFO topic
if (key != null) {
builder.groupId(key);
}
try {
operations.sendNotification(routing.getTarget(), builder.build());
} catch (MessageDeliveryException e) {
// message delivery may fail if groupId is set and topic is not a FIFO topic, or content based deduplication has not been set on topic attributes.
if (e.getCause() instanceof InvalidParameterException) {
logger.error("Failed to send notification to SNS topic {}:{}", routing.getTarget(), e.getCause().getMessage());
}
throw e;
}
});
}
}

View File

@@ -0,0 +1,5 @@
/**
* SNS event externalization support.
*/
@org.springframework.lang.NonNullApi
package org.springframework.modulith.events.aws.sns;

View File

@@ -0,0 +1 @@
org.springframework.modulith.events.aws.sns.SnsEventExternalizerConfiguration

View File

@@ -0,0 +1,64 @@
/*
* Copyright 2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.modulith.events.aws.sns;
import io.awspring.cloud.sns.core.SnsOperations;
import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.modulith.events.EventExternalizationConfiguration;
import org.springframework.modulith.events.support.DelegatingEventExternalizer;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
/**
* Integration tests for {@link SnsEventExternalizerConfiguration}.
*
* @author Maciej Walkowiak
* @since 1.1
*/
class SnsEventExternalizerConfigurationIntegrationTests {
@Test // GH-342
void registersExternalizerByDefault() {
basicSetup()
.run(ctxt -> {
assertThat(ctxt).hasSingleBean(DelegatingEventExternalizer.class);
});
}
@Test // GH-342
void disablesExternalizationIfConfigured() {
basicSetup()
.withPropertyValues("spring.modulith.events.externalization.enabled=false")
.run(ctxt -> {
assertThat(ctxt).doesNotHaveBean(DelegatingEventExternalizer.class);
});
}
private ApplicationContextRunner basicSetup() {
return new ApplicationContextRunner()
.withConfiguration(
AutoConfigurations.of(SnsEventExternalizerConfiguration.class))
.withBean(EventExternalizationConfiguration.class, () -> EventExternalizationConfiguration.disabled())
.withBean(SnsOperations.class, () -> mock(SnsOperations.class));
}
}

View File

@@ -0,0 +1,170 @@
/*
* Copyright 2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.modulith.events.aws.sns;
import java.util.Map;
import lombok.RequiredArgsConstructor;
import org.junit.jupiter.api.Test;
import org.testcontainers.containers.localstack.LocalStackContainer;
import org.testcontainers.utility.DockerImageName;
import software.amazon.awssdk.services.sns.SnsClient;
import software.amazon.awssdk.services.sqs.SqsAsyncClient;
import software.amazon.awssdk.services.sqs.model.QueueAttributeName;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.annotation.Bean;
import org.springframework.modulith.events.ApplicationModuleListener;
import org.springframework.modulith.events.Externalized;
import org.springframework.test.context.DynamicPropertyRegistry;
import org.springframework.transaction.annotation.Transactional;
import static org.assertj.core.api.Assertions.assertThat;
import static org.awaitility.Awaitility.await;
/**
* Integration tests for SQS-based event publication.
*
* @author Maciej Walkowiak
*/
@SpringBootTest
class SnsEventPublicationIntegrationTests {
@Autowired TestPublisher publisher;
@Autowired SnsClient snsClient;
@Autowired SqsAsyncClient sqsAsyncClient;
@SpringBootApplication
static class TestConfiguration {
@Bean
LocalStackContainer localStackContainer(DynamicPropertyRegistry registry) {
var localstack = new LocalStackContainer(DockerImageName.parse("localstack/localstack:2.3.2"));
registry.add("spring.cloud.aws.endpoint", localstack::getEndpoint);
registry.add("spring.cloud.aws.credentials.access-key", localstack::getAccessKey);
registry.add("spring.cloud.aws.credentials.secret-key", localstack::getSecretKey);
registry.add("spring.cloud.aws.region.static", localstack::getRegion);
return localstack;
}
@Bean
TestPublisher testPublisher(ApplicationEventPublisher publisher) {
return new TestPublisher(publisher);
}
@Bean
TestListener testListener() {
return new TestListener();
}
}
@Test
void publishesEventToSns() {
var topicArn = snsClient.createTopic(request -> request.name("target")).topicArn();
var queueUrl = sqsAsyncClient.createQueue(request -> request.queueName("queue"))
.join()
.queueUrl();
var queueArn = sqsAsyncClient
.getQueueAttributes(r -> r.queueUrl(queueUrl).attributeNames(QueueAttributeName.QUEUE_ARN))
.join().attributes().get(QueueAttributeName.QUEUE_ARN);
snsClient.subscribe(r -> r.topicArn(topicArn).protocol("sqs").endpoint(queueArn));
publisher.publishEvent();
await().untilAsserted(() -> {
var response = sqsAsyncClient.receiveMessage(r -> r.queueUrl(queueUrl)).join();
assertThat(response.hasMessages()).isTrue();
});
}
@Test
void publishesEventWithGroupIdToSns() {
var topicArn = snsClient.createTopic(request -> request.name("target.fifo")
.attributes(Map.of(
"FifoTopic", "true",
"ContentBasedDeduplication", "true"
)))
.topicArn();
var queueUrl = sqsAsyncClient.createQueue(request -> request.queueName("queue.fifo")
.attributes(Map.of(QueueAttributeName.FIFO_QUEUE, "true")))
.join()
.queueUrl();
var queueArn = sqsAsyncClient
.getQueueAttributes(r -> r.queueUrl(queueUrl).attributeNames(QueueAttributeName.QUEUE_ARN))
.join().attributes().get(QueueAttributeName.QUEUE_ARN);
snsClient.subscribe(r -> r.topicArn(topicArn).protocol("sqs").endpoint(queueArn));
publisher.publishEventWithKey();
await().untilAsserted(() -> {
var response = sqsAsyncClient.receiveMessage(r -> r.queueUrl(queueUrl)).join();
assertThat(response.hasMessages()).isTrue();
});
}
@Externalized("target")
static class TestEvent { }
@Externalized("target.fifo::#{getKey()}")
static class TestEventWithKey {
private final String key;
TestEventWithKey(String key) {
this.key = key;
}
public String getKey() {
return key;
}
}
@RequiredArgsConstructor
static class TestPublisher {
private final ApplicationEventPublisher events;
@Transactional
void publishEvent() {
events.publishEvent(new TestEvent());
}
@Transactional
void publishEventWithKey() {
events.publishEvent(new TestEventWithKey("aKey"));
}
}
static class TestListener {
@ApplicationModuleListener
void on(TestEvent event) {
}
@ApplicationModuleListener
void on(TestEventWithKey event) {
}
}
}

View File

@@ -0,0 +1 @@
spring.modulith.events.jdbc.schema-initialization.enabled=true

View File

@@ -0,0 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<property name="CONSOLE_LOG_PATTERN" value="%d{HH:mm:ss.SSS} %1.-1level - %8.8t : %m%n%wEx" />
<include resource="org/springframework/boot/logging/logback/defaults.xml" />
<include resource="org/springframework/boot/logging/logback/console-appender.xml" />
<root level="INFO">
<appender-ref ref="CONSOLE" />
</root>
<logger name="org.springframework.modulith" level="INFO" />
<logger name="io.awspring.cloud.sns" level="INFO" />
</configuration>

View File

@@ -0,0 +1,90 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.modulith</groupId>
<artifactId>spring-modulith-events</artifactId>
<version>1.1.0-SNAPSHOT</version>
</parent>
<name>Spring Modulith - Events - AWS SQS support</name>
<artifactId>spring-modulith-events-aws-sqs</artifactId>
<properties>
<module.name>org.springframework.modulith.events.aws.sqs</module.name>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.modulith</groupId>
<artifactId>spring-modulith-api</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.modulith</groupId>
<artifactId>spring-modulith-events-core</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>io.awspring.cloud</groupId>
<artifactId>spring-cloud-aws-sqs</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<optional>true</optional>
</dependency>
<!-- Test dependencies -->
<dependency>
<groupId>org.springframework.modulith</groupId>
<artifactId>spring-modulith-starter-jdbc</artifactId>
<version>${project.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-json</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-testcontainers</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.awspring.cloud</groupId>
<artifactId>spring-cloud-aws-starter-sqs</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>localstack</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@@ -0,0 +1,74 @@
/*
* Copyright 2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.modulith.events.aws.sqs;
import io.awspring.cloud.sqs.operations.SqsOperations;
import io.awspring.cloud.sqs.operations.SqsTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.expression.BeanFactoryResolver;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.modulith.events.EventExternalizationConfiguration;
import org.springframework.modulith.events.config.EventExternalizationAutoConfiguration;
import org.springframework.modulith.events.support.BrokerRouting;
import org.springframework.modulith.events.support.DelegatingEventExternalizer;
/**
* Auto-configuration to set up a {@link DelegatingEventExternalizer} to externalize events to SQS.
*
* @author Maciej Walkowiak
* @since 1.1
*/
@AutoConfiguration
@AutoConfigureAfter(EventExternalizationAutoConfiguration.class)
@ConditionalOnClass(SqsTemplate.class)
@ConditionalOnProperty(name = "spring.modulith.events.externalization.enabled",
havingValue = "true",
matchIfMissing = true)
class SqsEventExternalizerConfiguration {
private static final Logger logger = LoggerFactory.getLogger(SqsEventExternalizerConfiguration.class);
@Bean
DelegatingEventExternalizer sqsEventExternalizer(EventExternalizationConfiguration configuration,
SqsOperations operations, BeanFactory factory) {
logger.debug("Registering domain event externalization to SQS…");
var context = new StandardEvaluationContext();
context.setBeanResolver(new BeanFactoryResolver(factory));
return new DelegatingEventExternalizer(configuration, (target, payload) -> {
var routing = BrokerRouting.of(target, context);
operations.send(sqsSendOptions -> {
var options = sqsSendOptions.queue(routing.getTarget()).payload(payload);
var key = routing.getKey(payload);
if (key != null) {
options.messageGroupId(key);
}
});
});
}
}

View File

@@ -0,0 +1,5 @@
/**
* SQS event externalization support.
*/
@org.springframework.lang.NonNullApi
package org.springframework.modulith.events.aws.sqs;

View File

@@ -0,0 +1 @@
org.springframework.modulith.events.aws.sqs.SqsEventExternalizerConfiguration

View File

@@ -0,0 +1,64 @@
/*
* Copyright 2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.modulith.events.aws.sqs;
import io.awspring.cloud.sqs.operations.SqsOperations;
import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.modulith.events.EventExternalizationConfiguration;
import org.springframework.modulith.events.support.DelegatingEventExternalizer;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
/**
* Integration tests for {@link SqsEventExternalizerConfiguration}.
*
* @author Maciej Walkowiak
* @since 1.1
*/
class SqsEventExternalizerConfigurationIntegrationTests {
@Test // GH-342
void registersExternalizerByDefault() {
basicSetup()
.run(ctxt -> {
assertThat(ctxt).hasSingleBean(DelegatingEventExternalizer.class);
});
}
@Test // GH-342
void disablesExternalizationIfConfigured() {
basicSetup()
.withPropertyValues("spring.modulith.events.externalization.enabled=false")
.run(ctxt -> {
assertThat(ctxt).doesNotHaveBean(DelegatingEventExternalizer.class);
});
}
private ApplicationContextRunner basicSetup() {
return new ApplicationContextRunner()
.withConfiguration(
AutoConfigurations.of(SqsEventExternalizerConfiguration.class))
.withBean(EventExternalizationConfiguration.class, () -> EventExternalizationConfiguration.disabled())
.withBean(SqsOperations.class, () -> mock(SqsOperations.class));
}
}

View File

@@ -0,0 +1,148 @@
/*
* Copyright 2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.modulith.events.aws.sqs;
import java.util.Map;
import lombok.RequiredArgsConstructor;
import org.junit.jupiter.api.Test;
import org.testcontainers.containers.localstack.LocalStackContainer;
import org.testcontainers.utility.DockerImageName;
import software.amazon.awssdk.services.sqs.SqsAsyncClient;
import software.amazon.awssdk.services.sqs.model.QueueAttributeName;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.annotation.Bean;
import org.springframework.modulith.events.ApplicationModuleListener;
import org.springframework.modulith.events.Externalized;
import org.springframework.test.context.DynamicPropertyRegistry;
import org.springframework.transaction.annotation.Transactional;
import static org.assertj.core.api.Assertions.assertThat;
import static org.awaitility.Awaitility.await;
/**
* Integration tests for SQS-based event publication.
*
* @author Maciej Walkowiak
*/
@SpringBootTest
class SqsEventPublicationIntegrationTests {
@Autowired TestPublisher publisher;
@Autowired SqsAsyncClient sqsAsyncClient;
@SpringBootApplication
static class TestConfiguration {
@Bean
LocalStackContainer localStackContainer(DynamicPropertyRegistry registry) {
var localstack = new LocalStackContainer(DockerImageName.parse("localstack/localstack:2.3.2"));
registry.add("spring.cloud.aws.endpoint", localstack::getEndpoint);
registry.add("spring.cloud.aws.credentials.access-key", localstack::getAccessKey);
registry.add("spring.cloud.aws.credentials.secret-key", localstack::getSecretKey);
registry.add("spring.cloud.aws.region.static", localstack::getRegion);
return localstack;
}
@Bean
TestPublisher testPublisher(ApplicationEventPublisher publisher) {
return new TestPublisher(publisher);
}
@Bean
TestListener testListener() {
return new TestListener();
}
}
@Test
void publishesEventToSqs() throws Exception {
var queueUrl = sqsAsyncClient.createQueue(request -> request.queueName("target"))
.join()
.queueUrl();
publisher.publishEvent();
await().untilAsserted(() -> {
var response = sqsAsyncClient.receiveMessage(r -> r.queueUrl(queueUrl)).join();
assertThat(response.hasMessages()).isTrue();
});
}
@Test
void publishesEventWithGroupIdToSqs() throws Exception {
var queueUrl = sqsAsyncClient.createQueue(request -> request.queueName("target.fifo")
.attributes(Map.of(QueueAttributeName.FIFO_QUEUE, "true")))
.join()
.queueUrl();
publisher.publishEventWithKey();
await().untilAsserted(() -> {
var response = sqsAsyncClient.receiveMessage(r -> r.queueUrl(queueUrl)).join();
assertThat(response.hasMessages()).isTrue();
});
}
@Externalized("target")
static class TestEvent {}
@Externalized("target.fifo::#{getKey()}")
static class TestEventWithKey {
private final String key;
TestEventWithKey(String key) {
this.key = key;
}
public String getKey() {
return key;
}
}
@RequiredArgsConstructor
static class TestPublisher {
private final ApplicationEventPublisher events;
@Transactional
void publishEvent() {
events.publishEvent(new TestEvent());
}
@Transactional
void publishEventWithKey() {
events.publishEvent(new TestEventWithKey("aKey"));
}
}
static class TestListener {
@ApplicationModuleListener
void on(TestEvent event) {}
@ApplicationModuleListener
void on(TestEventWithKey event) {}
}
}

View File

@@ -0,0 +1,2 @@
spring.artemis.embedded.topics=target
spring.modulith.events.jdbc.schema-initialization.enabled=true

View File

@@ -0,0 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<property name="CONSOLE_LOG_PATTERN" value="%d{HH:mm:ss.SSS} %1.-1level - %8.8t : %m%n%wEx" />
<include resource="org/springframework/boot/logging/logback/defaults.xml" />
<include resource="org/springframework/boot/logging/logback/console-appender.xml" />
<root level="INFO">
<appender-ref ref="CONSOLE" />
</root>
<logger name="org.springframework.modulith" level="INFO" />
<logger name="io.awspring.cloud.sqs" level="INFO" />
</configuration>

View File

@@ -316,6 +316,18 @@ The logical routing key will be used as AMQP routing key.
|`spring-modulith-events-jms`
|Uses Spring's core JMS support.
Does not support routing keys.
|SQS
|`spring-modulith-events-aws-sqs`
|Uses Spring Cloud AWS SQS support.
The logical routing key will be used as SQS message group id.
When routing key is set, requires SQS queue to be configured as a FIFO queue.
|SNS
|`spring-modulith-events-aws-sns`
|Uses Spring Cloud AWS SNS support.
The logical routing key will be used as SNS message group id.
When routing key is set, requires SNS to be configured as a FIFO topic with content based deduplication enabled.
|===
[[externalization.fundamentals]]