반응형
SpringBoot에서 SNS로 메세지 발행하기
SQS로 받은 메시지 Springboot에서 받아보기
개발환경 : Intellij, java17, gradle
1. 의존성 설정
implementation 'org.springframework.boot:spring-boot-starter-data-redis'
implementation 'org.springframework.boot:spring-boot-starter-web'
developmentOnly 'org.springframework.boot:spring-boot-devtools'
annotationProcessor 'org.springframework.boot:spring-boot-configuration-processor'
annotationProcessor 'org.projectlombok:lombok'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
implementation 'com.google.code.gson:gson:2.9.0'
implementation platform('software.amazon.awssdk:bom:2.15.0')
implementation group: 'org.springframework.cloud', name: 'spring-cloud-aws-messaging', version: '2.2.1.RELEASE'
implementation 'software.amazon.awssdk:sns'
implementation 'software.amazon.awssdk:sqs'
implementation 'org.springframework.cloud:spring-cloud-starter-aws:2.2.6.RELEASE'
2. application.yml
${AWS_ACCESSKEY} 는 intellij 환경변수에 등록해서 사용함
intellij 환경변수 추가는 https://mchch.tistory.com/282 참고
cloud:
aws:
credentials:
access-key: ${AWS_ACCESSKEY}
secret-key: ${AWS_SECRETKEY}
region:
static: ap-northeast-1
auto: false
stack:
auto: false
sns:
topic:
arn: arn:aws:sns:ap-northeast-1:34243243247:MyTopic2
sqs:
queue:
name: MyQueue2
url: https://sqs.ap-northeast-1.amazonaws.com/34243243247/MyQueue2
3. AWSConfig.java
@Getter
@Configuration
public class AWSConfig {
@Value("${cloud.aws.credentials.access-key}")
private String awsAccessKey;
@Value("${cloud.aws.credentials.secret-key}")
private String awsSecretKey;
@Value("${cloud.aws.region.static}")
private String awsRegion;
@Value("${cloud.aws.sns.topic.arn}")
private String snsTopicARN;
@Bean // SNS Client 세팅
public SnsClient getSnsClient() {
return SnsClient.builder()
.credentialsProvider(
getAwsCredentials(this.awsAccessKey, this.awsSecretKey)
).region(Region.of(this.awsRegion))
.build();
}
//aws credential 세팅
public AwsCredentialsProvider getAwsCredentials(String accessKeyID, String secretAccessKey) {
AwsBasicCredentials awsBasicCredentials = AwsBasicCredentials.create(accessKeyID, secretAccessKey);
return () -> awsBasicCredentials;
}
@Bean // SQS Client 세팅
public AmazonSQS amazonSQS() {
AWSCredentials credentials = new BasicAWSCredentials(awsAccessKey, awsSecretKey);
return AmazonSQSAsyncClientBuilder
.standard()
.withCredentials(new AWSStaticCredentialsProvider(credentials))
.withRegion(awsRegion)
.build();
}
}
4. SnsService.java
지정한 topic으로 메세지 발행하는 서비스
@Service
@RequiredArgsConstructor
public class SnsService {
private final AWSSnsConfig awsConfig;
public PublishResponse awsSnsPublishTest(Map<String,Object> scriptData) {
PublishRequest publishRequest = PublishRequest.builder()
.topicArn(awsConfig.getSnsTopicARN())
.subject("TEST 제목")
.message(scriptData.toString())
.build();
SnsClient snsClient = awsConfig.getSnsClient();
PublishResponse publishResponse = snsClient.publish(publishRequest);
snsClient.close();
return publishResponse;
}
}
5. SqsService.java
sns 토픽에서 메세지 가져오는 sqs서비스
@Service
public class SqsService {
private final QueueMessagingTemplate queueMessagingTemplate;
@Autowired
public SqsService(AmazonSQS amazonSqs) {
this.queueMessagingTemplate = new QueueMessagingTemplate((AmazonSQSAsync) amazonSqs);
}
public void getMessage() {
String rr = queueMessagingTemplate.receiveAndConvert("MyQueue2", String.class);
System.out.println("queue message :: " + rr );
}
}
6. SqsListener.java
@Component
public class SqlListener {
@SqsListener(value = "MyQueue2", deletionPolicy = SqsMessageDeletionPolicy.NEVER)
public void listen(@Payload String sst, Acknowledgment ack) {
log.info("{}", sst);
ack.acknowledge();
}
}
7. Controller.java
서비스 호출 controller.
@RestController
@RequiredArgsConstructor
@RequestMapping("api")
public class SnsController {
private final SnsService snsService;
private final SqsService sqsService;
//메세지 발행 메소드
@PostMapping("/publish")
public void publish(@RequestBody Map<String, Object> scriptData) {
PublishResponse pr = snsService.awsSnsPublishTest(scriptData);
System.out.println(pr);
//PublishResponse(MessageId=80da361c-4ec9-55f5-9aa8-6a49037995af)
}
//메세지 가져오는 메소드
@GetMapping("/subscribe")
public void getMessage() {
sqsService.getMessage();
}
}
가져온 메세지 콘솔출력
반응형
'코딩 관련 > AWS' 카테고리의 다른 글
Spring boot 서비스에서 MSK IAM 인증 연결 / springboot MSK 연동 (0) | 2024.01.31 |
---|---|
software.amazon.awssdk.services.sns.model.InvalidParameterException: Invalid parameter: TopicArn (0) | 2023.02.02 |
AWS SNS SQS 사용법 / SNS SQS 연동 (0) | 2023.02.01 |