当前位置: 首页 > 工具软件 > sns4j > 使用案例 >

JAVA 整合 AWS SNS发送短信[Amazon Simple Notification Service]

夹谷硕
2023-12-01

转载请表明出处 https://blog.csdn.net/Amor_Leo/article/details/117957784 谢谢

java整合aws sns发送短信

pom


    <properties>
            <aws-sns.version>1.12.5</aws-sns.version>
    </properties>

        <!-- AWS SNS-->
        <dependency>
            <groupId>com.amazonaws</groupId>
            <artifactId>aws-java-sdk-sns</artifactId>
            <version>${aws-sns.version}</version>
        </dependency>

yml

# aws sns
sns:
  accessKeyId: xxxxx
  secretKey: xxxx

工具类

import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.sns.AmazonSNS;
import com.amazonaws.services.sns.AmazonSNSClientBuilder;
import com.amazonaws.services.sns.model.MessageAttributeValue;
import com.amazonaws.services.sns.model.PublishRequest;
import com.amazonaws.services.sns.model.PublishResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;

/**
 * aws sns短信发送
 * @author LHL
 * @since 2021/5/31
 */
@Component
@Slf4j
public class SnsMessageUtil {

    private Map<String, MessageAttributeValue> smsAttributes;

    private static String AWS_ACCESS_KEY_ID;

    private static String AWS_SECRET_KEY;


    @Value("${sns.accessKeyId}")
    public void setKeyId(String keyId) {
        AWS_ACCESS_KEY_ID = keyId;
    }

    @Value("${sns.secretKey}")
    public void setKey(String key) {
        AWS_SECRET_KEY = key;
    }

    /**
     * 发送短信 aws sns
     *
     * @author LHL
     * @since 2021/5/31
     * @param phoneNumber 手机号
     * @param message 消息
     * @return boolean
     */
    public boolean send2Sns(String phoneNumber, String message) {
        if (phoneNumber.contains("_")) {
            phoneNumber = StringUtils.replace(phoneNumber, "_", "");
        }
        if (phoneNumber.contains("-")) {
            phoneNumber = StringUtils.replace(phoneNumber, "-", "");
        }
        if (!phoneNumber.startsWith("+")) {
            phoneNumber = "+" + phoneNumber;
        }
        // 手机号需带国际区号
        PublishResult result = sendSmsMessage(phoneNumber, message, getDefaultSmsAttributes());
        // Prints the message ID.
        log.info("message ID: {}", result.getMessageId());
        return StringUtils.isNotBlank(result.getMessageId());
    }

    public Map<String, MessageAttributeValue> getDefaultSmsAttributes() {
        if (smsAttributes == null) {
            smsAttributes = new HashMap<>();
            smsAttributes.put("AWS.SNS.SMS.SenderID", new MessageAttributeValue()
                    .withStringValue("1")
                    .withDataType("String"));
            smsAttributes.put("AWS.SNS.SMS.MaxPrice", new MessageAttributeValue()
                    .withStringValue("0.05")
                    .withDataType("Number"));
            smsAttributes.put("AWS.SNS.SMS.SMSType", new MessageAttributeValue()
                    .withStringValue("Transactional")
                    .withDataType("String"));
        }
        return smsAttributes;
    }


    public PublishResult sendSmsMessage(String phoneNumber, String message, Map<String, MessageAttributeValue> smsAttributes) {
        AWSCredentials awsCredentials = new AWSCredentials() {
            @Override
            public String getAWSAccessKeyId() {
                // 带有发短信权限的 IAM 的 ACCESS_KEY
                return AWS_ACCESS_KEY_ID;
            }

            @Override
            public String getAWSSecretKey() {
                // 带有发短信权限的 IAM 的 SECRET_KEY
                return AWS_SECRET_KEY;
            }

        };
        AWSCredentialsProvider provider = new AWSCredentialsProvider() {
            @Override
            public AWSCredentials getCredentials() {
                return awsCredentials;
            }

            @Override
            public void refresh() {
            }
        };
        AmazonSNS amazonSNS = null;
        try {
            //设置aws区域
            amazonSNS = AmazonSNSClientBuilder.standard().withCredentials(provider).withRegion(Regions.US_EAST_1.getName()).build();
        } catch (Exception e) {
            log.error("amazonSNS error msg: {}", e.getMessage());
        }
        assert amazonSNS != null;
        return amazonSNS.publish(
                new PublishRequest()
                        .withMessage(message)
                        .withPhoneNumber(phoneNumber)
                        .withMessageAttributes(smsAttributes)
        );
    }


}

 类似资料: