我无法使用 Spring Boot 和 SQS 制作工作队列侦听器(消息已发送并出现在 SQS ui 中)
或@MessageMapping
不@SqsListener
工作
Java:11
Spring Boot:2.1.7
依赖:spring-cloud-aws-messaging
这是我的配置
@Configuration
@EnableSqs
public class SqsConfig {
@Value("#{'${env.name:DEV}'}")
private String envName;
@Value("${cloud.aws.region.static}")
private String region;
@Value("${cloud.aws.credentials.access-key}")
private String awsAccessKey;
@Value("${cloud.aws.credentials.secret-key}")
private String awsSecretKey;
@Bean
public Headers headers() {
return new Headers();
}
@Bean
public MessageQueue queueMessagingSqs(Headers headers,
QueueMessagingTemplate queueMessagingTemplate) {
Sqs queue = new Sqs();
queue.setQueueMessagingTemplate(queueMessagingTemplate);
queue.setHeaders(headers);
return queue;
}
private ResourceIdResolver getResourceIdResolver() {
return queueName -> envName + "-" + queueName;
}
@Bean
public DestinationResolver destinationResolver(AmazonSQSAsync amazonSQSAsync) {
DynamicQueueUrlDestinationResolver destinationResolver = new DynamicQueueUrlDestinationResolver(
amazonSQSAsync,
getResourceIdResolver());
destinationResolver.setAutoCreate(true);
return destinationResolver;
}
@Bean
public QueueMessagingTemplate queueMessagingTemplate(AmazonSQSAsync amazonSQSAsync,
DestinationResolver destinationResolver) {
return new QueueMessagingTemplate(amazonSQSAsync, destinationResolver, null);
}
@Bean
public QueueMessageHandlerFactory queueMessageHandlerFactory() {
QueueMessageHandlerFactory factory = new QueueMessageHandlerFactory();
MappingJackson2MessageConverter messageConverter = new MappingJackson2MessageConverter();
messageConverter.setStrictContentTypeMatch(false);
factory.setArgumentResolvers(Collections.singletonList(new PayloadArgumentResolver(messageConverter)));
return factory;
}
@Bean
public SimpleMessageListenerContainerFactory simpleMessageListenerContainerFactory(AmazonSQSAsync amazonSqs) {
SimpleMessageListenerContainerFactory factory = new SimpleMessageListenerContainerFactory();
factory.setAmazonSqs(amazonSqs);
factory.setMaxNumberOfMessages(10);
factory.setWaitTimeOut(2);
return factory;
}
}
我也注意到org.springframework.cloud.aws.messaging.config.SimpleMessageListenerContainerFactory
并org.springframework.cloud.aws.messaging.config.annotation.SqsConfiguration
在启动时运行
还有我的测试
@RunWith(SpringJUnit4ClassRunner.class)
public class ListenTest {
@Autowired
private MessageQueue queue;
private final String queueName = "test-queue-receive";
private String result = null;
@Test
public void test_listen() {
// given
String data = "abc";
// when
queue.send(queueName, data).join();
// then
Awaitility.await()
.atMost(10, TimeUnit.SECONDS)
.until(() -> Objects.nonNull(result));
Assertions.assertThat(result).equals(data);
}
@MessageMapping(value = queueName)
public void receive(String data) {
this.result = data;
}
}
你觉得有什么不对吗?
我为示例创建了一个存储库:(https://github.com/mmaryo/java-sqs-test)
在测试文件夹中,更改 'application.yml' 中的 aws 凭据,
然后运行测试