我们当前正在从 SQS 队列发送/接收消息。从提供 access_key、secret_access_key、session_token 的
.aws/credentials
文件加载凭据。几个小时后,凭据就会过期,所以我想知道如何刷新这些凭据而无需手动干预。
AWS SQS 配置:
@Configuration
public class AwsSqsConfig {
@Value("${spring.cloud.aws.region.static}")
private String region;
@Value("${spring.cloud.aws.sqs.endpoint}")
private String endpoint;
@Value("${spring.cloud.aws.credentials.profile.name}")
String profileName;
@Bean
public AwsCredentialsProvider awsCredentialsProvider() {
return ProfileCredentialsProvider
.builder()
.profileName(profileName)
.build();
}
@Bean
SqsAsyncClient sqsAsyncClient(AwsCredentialsProvider awsCredentialsProvider) throws URISyntaxException {
return SqsAsyncClient.builder()
.endpointOverride(new URI(endpoint))
.region(Region.of(region))
.credentialsProvider(awsCredentialsProvider)
.build();
}
@Bean
public SqsTemplate sqsTemplate(SqsAsyncClient sqsAsyncClient) {
return SqsTemplate.builder().sqsAsyncClient(sqsAsyncClient).build();
}
}
SQS消息监听器:
@Component
@AllArgsConstructor
public class SQSMessageListener {
private static final Logger log = LoggerFactory.getLogger(SQSMessageListener.class);
private ThreadPoolTaskScheduler threadPoolTaskScheduler;
private SqsTemplate sqsTemplate;
@SqsListener("check-event-status")
public void receiveCheckEventStatusMessage(String message) {
log.trace("Received check event status message: {}", message);
// Logic below...
}
@SqsListener("update-service")
public void receiveUpdateServiceMessage(String message) {
log.trace("Received update service message: {}", message);
// Logic below...
}
@SqsListener("creation")
public void receiveCreationMessage(String message) {
log.trace("Received creation message: {}", message);
// Logic below...
}
@SqsListener("execution")
public void receiveExecutionMessage(String message) {
log.trace("Received execution message: {}", message);
// Logic below...
}
}
创作任务:
@Component
@AllArgsConstructor
public class CreationTask implements Runnable {
private static final Logger log = LoggerFactory.getLogger(CreationTask.class);
private SqsTemplate sqsTemplate;
@Override
public void run() {
log.trace("Running CreationTask");
log.trace("Sending payload-1");
String payload1 = Status.SCHEDULED.name() + ":1";
sqsTemplate.send(sqsSendOptions -> sqsSendOptions.queue("execution").payload(payload1));
log.trace("Sending payload-2");
String payload2 = Status.INPROGRESS.name() + ":2";
sqsTemplate.send(sqsSendOptions -> sqsSendOptions.queue("execution").payload(payload2));
log.trace("Sending payload-3");
String payload3 = Status.CLOSED.name() + ":3";
sqsTemplate.send(sqsSendOptions -> sqsSendOptions.queue("execution").payload(payload3));
}
}
要自动刷新您的 AWS 凭证而无需手动干预,您可以使用 AWS Security Token Service (STS) 担任提供临时安全凭证的角色。这是一般方法:
• 创建 IAM 角色:确保您拥有一个具有访问 SQS 队列所需权限的 IAM 角色。
• 使用 AWS STS 代入角色:使用 AssumeRole API 获取临时安全凭证。这些凭证包括访问密钥 ID、秘密访问密钥和安全令牌。
• 自动凭据刷新:实施脚本或使用库在这些凭据过期之前定期刷新这些凭据。您可以使用您首选编程语言的 AWS 开发工具包来处理此问题。