阿里云短信服务_Java实现

pom.xml引入依赖

    <dependency>
        <groupId>com.aliyun</groupId>
        <artifactId>alibabacloud-dysmsapi20170525</artifactId>
        <version>2.0.23</version>
    </dependency>
@Component
public class AliSms {

    private static AsyncClient client;
    private static final StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
        .accessKeyId("")
        .accessKeySecret("")
        .build());

    @PostConstruct
    public void init() {
        client = AsyncClient.builder()
            .region("cn-shanghai")
            .credentialsProvider(provider)
            .overrideConfiguration(
                ClientOverrideConfiguration.create()
                    .setEndpointOverride("dysmsapi.aliyuncs.com"))
            .build();
    }

    public void sendVerifyCode(String tel, String code) throws ExecutionException, InterruptedException {
        SendSmsRequest request = buildRequest(tel, code);
        CompletableFuture<SendSmsResponse> resp = client.sendSms(request);
        checkResponse(resp);
    }

    private SendSmsRequest buildRequest(String tel, String code) {
        return SendSmsRequest.builder()
            .signName("xx个人博客")
            .templateParam(String.format("{\"code\":\"%s\"}", code))
            .phoneNumbers(tel)
            .templateCode("SMS_274780173")
            .build();
    }

    private void checkResponse(CompletableFuture<SendSmsResponse> resp) throws ExecutionException, InterruptedException {
        if (!"OK".equals(resp.get().getBody().getCode())) {
            throw new BusinessException(String.format("【阿里云】%s",resp.get().getBody().getMessage()));
        }
    }

    @PreDestroy
    public void destroy() throws IOException {
        if(client !=null){
            client.close();
        }
    }
}

 

参考

 
posted @ 2023-07-10 10:50  Ashe|||^_^  阅读(16)  评论(0编辑  收藏  举报