首页 /  技术专区  /  SpringBoot 宽屏模式 >

SpringBoot 使用阿里云 SMS 发送短信

第一步:导入Maven依赖

<dependency>
    <groupId>com.aliyun</groupId>
    <artifactId>alibabacloud-dysmsapi20170525</artifactId>
    <version>2.0.24</version>
</dependency>

第二步:配置application.yaml

image.png

# 阿里云发送短息
aliyunSms:
  accessKeyId:你自己的accessKeyId
  accessKeySecret: 你自己的accessKeySecret
  # 控制是否发送短信,dev 开发环境可以设置为 false,节省短信费用
  enable: true

第三步:编写配置类

import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsResponse;
import com.google.gson.Gson;
import darabonba.core.client.ClientOverrideConfiguration;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

@Component
public class SendSms {

    @Value("${aliyunSms.accessKeyId}")
    private String accessKeyId;

    @Value("${aliyunSms.accessKeySecret}")
    private String accessKeySecret;

    @Value("${aliyunSms.enable}")
    private Boolean enable;

    /**
     * 发送短信
     *
     * @param phoneNumbers  手机号
     * @param signName      签名名称
     * @param templateCode  模板 id
     * @param templateParam 模板内容
     * @throws ExecutionException   异常
     * @throws InterruptedException 异常
     */
    public String send(String phoneNumbers, String signName, String templateCode, String templateParam) throws ExecutionException, InterruptedException {
        // HttpClient Configuration
        /* HttpClient httpClient = new ApacheAsyncHttpClientBuilder()
                .connectionTimeout(Duration.ofSeconds(10)) // Set the connection timeout time, the default is 10 seconds
                .responseTimeout(Duration.ofSeconds(10)) // Set the response timeout time, the default is 20 seconds
                .maxConnections(128) // Set the connection pool size
                .maxIdleTimeOut(Duration.ofSeconds(50)) // Set the connection pool timeout, the default is 30 seconds
                // Configure the proxy
                .proxy(new ProxyOptions(ProxyOptions.Type.HTTP, new InetSocketAddress("<your-proxy-hostname>", 9001))
                        .setCredentials("<your-proxy-username>", "<your-proxy-password>"))
                // If it is an https connection, you need to configure the certificate, or ignore the certificate(.ignoreSSL(true))
                .x509TrustManagers(new X509TrustManager[]{})
                .keyManagers(new KeyManager[]{})
                .ignoreSSL(false)
                .build();*/

        // Configure Credentials authentication information, including ak, secret, token
        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                // Please ensure that the environment variables ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET are set.
                .accessKeyId(accessKeyId)
                .accessKeySecret(accessKeySecret)
                //.securityToken(System.getenv("ALIBABA_CLOUD_SECURITY_TOKEN")) // use STS token
                .build());

        // Configure the Client
        AsyncClient client = AsyncClient.builder()
                //.httpClient(httpClient) // Use the configured HttpClient, otherwise use the default HttpClient (Apache HttpClient)
                .credentialsProvider(provider)
                //.serviceConfiguration(Configuration.create()) // Service-level configuration
                // Client-level configuration rewrite, can set Endpoint, Http request parameters, etc.
                .overrideConfiguration(
                        ClientOverrideConfiguration.create()
                                // Endpoint 请参考 https://api.aliyun.com/product/Dysmsapi
                                .setEndpointOverride("dysmsapi.aliyuncs.com")
                        //.setConnectTimeout(Duration.ofSeconds(30))
                )
                .build();

        // Parameter settings for API request
        SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
                .phoneNumbers(phoneNumbers)
                .signName(signName)
                .templateCode(templateCode)
                .templateParam(templateParam)
                // Request-level configuration rewrite, can set Http request parameters, etc.
                // .requestConfiguration(RequestConfiguration.create().setHttpHeaders(new HttpHeaders()))
                .build();

        try {
            SendSmsResponse resp = null;
            if (enable) {
                // Asynchronously get the return value of the API request
                CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest);
                // Synchronously get the return value of the API request
                resp = response.get();
                System.out.println(new Gson().toJson(resp));
                // Asynchronous processing of return values
                /*response.thenAccept(resp -> {
                    System.out.println(new Gson().toJson(resp));
                }).exceptionally(throwable -> { // Handling exceptions
                    System.out.println(throwable.getMessage());
                    return null;
                });*/
                // Finally, close the client
                return new Gson().toJson(resp);
            } else {
                return "未开启验证码短信发送开关,不发送短信";
            }
        } finally {
            client.close();
        }
    }
}

第四步:调用发送短信接口

// 模板内容
Map<String, String> templateParam = new HashMap<>();
templateParam.put("code", code);
String res = sms.send("手机号", "签名", "消息模板", JSON.toJSONString(templateParam));

image.png


头像
0/200
图片验证码