阿里云短信服务详细说明与实战开发后端代码(三)

本文涉及的产品
Redis 开源版,标准版 2GB
推荐场景:
搭建游戏排行榜
云数据库 Tair(兼容Redis),内存型 2GB
国际/港澳台短信套餐包,全球plus 100条 6个月
简介: 阿里云短信服务详细说明与实战开发后端代码

9.自主测试Java SDK

8.在线测试签名模板API 中屏幕右边的代码进行拷贝自己运行即可:

<dependency>
  <groupId>com.aliyun</groupId>
  <artifactId>alibabacloud-dysmsapi20170525</artifactId>
  <version>2.0.23</version>
</dependency>
// This file is auto-generated, don't edit it. Thanks.
package demo;
import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.core.http.HttpClient;
import com.aliyun.core.http.HttpMethod;
import com.aliyun.core.http.ProxyOptions;
import com.aliyun.httpcomponent.httpclient.ApacheAsyncHttpClientBuilder;
import com.aliyun.sdk.service.dysmsapi20170525.models.*;
import com.aliyun.sdk.service.dysmsapi20170525.*;
import com.google.gson.Gson;
import darabonba.core.RequestConfiguration;
import darabonba.core.client.ClientOverrideConfiguration;
import darabonba.core.utils.CommonUtil;
import darabonba.core.TeaPair;
//import javax.net.ssl.KeyManager;
//import javax.net.ssl.X509TrustManager;
import java.net.InetSocketAddress;
import java.time.Duration;
import java.util.*;
import java.util.concurrent.CompletableFuture;
public class SendSms {
    public static void main(String[] args) throws Exception {
        // 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()
                .accessKeyId("<your-accessKeyId>")
                .accessKeySecret("<your-accessKeySecret>")
                //.securityToken("<your-token>") // use STS token
                .build());
        // Configure the Client
        AsyncClient client = AsyncClient.builder()
                .region("cn-wulanchabu") // Region ID
                //.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()
                                .setEndpointOverride("dysmsapi.aliyuncs.com")
                        //.setConnectTimeout(Duration.ofSeconds(30))
                )
                .build();
        // Parameter settings for API request
        SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
                .signName("逐浪教育")
                .templateCode("SMS_275395309")
                .phoneNumbers("18670082846")
                .templateParam("{\"code\":\"1234\"}")
                // Request-level configuration rewrite, can set Http request parameters, etc.
                // .requestConfiguration(RequestConfiguration.create().setHttpHeaders(new HttpHeaders()))
                .build();
        // Asynchronously get the return value of the API request
        CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest);
        // Synchronously get the return value of the API request
        SendSmsResponse 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
        client.close();
    }
}

10.⭐前后端实战开发-发送短信验证码

10.1 流程分析

10.2 配置参数说明

sms:
  ali:
    # 子用户的访问键
    accessKeyId: LTAI5tPBmf8y7ZoQSn9h****
    # 子用户的访问密钥
    accessKeySecret: cbd511ed24bd832d05af54f64c84****
    # 签名名称
    signName: 逐浪教育
    # 登录短信模板的code
    loginTemplateCode: SMS_27539****

10.2.1 访问键与密钥

就是在 4.3 创建子用户 中得到的 accessKeyId 与 accessKeySecret

10.2.2 签名名称

就是在 5.添加签名 中设置的签名内容。

10.2.3 登录短信模板code

10.3 🚀 后端代码

由于demo代码过多,这里不做展示。

实战demo源码地址:Mr-Write/SpringbootDemo: 各种demo案例 (github.com)

对应的是 sms-demo 包模块。

🍀 示例演示,用 Apipost7 进行测试:【POST】 http://127.0.0.1:10505/sms-ali/sendLoginCode

同时在我的手机上也接受到了验证码消息。

10.4 补充说明

10.4.1 调用 api 后响应的返回数据

名称 类型 描述 示例
Code String 请求状态码。返回OK代表请求成功。其他错误码,请参见[API错误码](https://help.aliyun.com/document_detail/101346.html?spm=api-workbench.API Document.0.0.5be349a5PlzN8a)。 OK
Message String 状态码的描述。 OK
BizId String 发送回执ID。可根据发送回执ID在接口QuerySendDetails中查询具体的发送状态。 9006197469364984****
RequestId String 请求ID。 F655A8D5-B967-440B-8683-DAD6FF8DE990

正常返回的JSON格式示例

{
  "Code": "OK",
  "Message": "OK",
  "BizId": "9006197469364984****",
  "RequestId": "F655A8D5-B967-440B-8683-DAD6FF8DE990"
}

10.4.2 application.yml 文件中的配置需要进行修改。

  • redis 地址
  • redis 密码
  • 短信平台信息

10.4.3 ubuntu安装docker的步骤

  1. 安装需要的包
sudo apt-get update
  1. 安装依赖包
sudo apt-get install \
   apt-transport-https \
   ca-certificates \
   curl \
   gnupg-agent \
   software-properties-common
  1. 添加 Docker 的官方 GPG 密钥
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
  1. 设置远程仓库
sudo add-apt-repository \
   "deb [arch=amd64] https://download.docker.com/linux/ubuntu \
  $(lsb_release -cs) \
  stable"
  1. 安装 Docker-CE
sudo apt-get update
sudo apt-get install docker-ce docker-ce-cli containerd.io
  1. 验证是否成功
sudo docker run hello-world

10.4.4 使用 docker 安装redis并设置密码的步骤

# 拉取redis镜像
docker pull redis
# 启动容器的时候,并为其设置密码
docker run -d --name myredis -p 6379:6379 redis --requirepass "123456"

10.4.5 其它注意事项

注意需要将服务器防火墙6379端口打开。

相关文章
|
8天前
|
API
阿里云短信服务文档与实际API不符
阿里云短信服务文档与实际API不符
|
1月前
|
数据采集 监控 安全
阿里云短信服务+图形认证,有效降低验证码盗刷概率
阿里云短信服务+图形认证服务,有效降低验证码盗刷概率。
166 3
阿里云短信服务+图形认证,有效降低验证码盗刷概率
|
16天前
|
机器学习/深度学习 PyTorch 算法框架/工具
揭秘深度学习中的微调难题:如何运用弹性权重巩固(EWC)策略巧妙应对灾难性遗忘,附带实战代码详解助你轻松掌握技巧
【10月更文挑战第1天】深度学习中,模型微调虽能提升性能,但常导致“灾难性遗忘”,即模型在新任务上训练后遗忘旧知识。本文介绍弹性权重巩固(EWC)方法,通过在损失函数中加入正则项来惩罚对重要参数的更改,从而缓解此问题。提供了一个基于PyTorch的实现示例,展示如何在训练过程中引入EWC损失,适用于终身学习和在线学习等场景。
36 4
揭秘深度学习中的微调难题:如何运用弹性权重巩固(EWC)策略巧妙应对灾难性遗忘,附带实战代码详解助你轻松掌握技巧
|
9天前
|
jenkins Java 测试技术
如何使用 Jenkins 自动发布 Java 代码,通过一个电商公司后端服务的实际案例详细说明
【10月更文挑战第8天】本文介绍了如何使用 Jenkins 自动发布 Java 代码,通过一个电商公司后端服务的实际案例,详细说明了从 Jenkins 安装配置到自动构建、测试和部署的全流程。文中还提供了一个 Jenkinsfile 示例,并分享了实践经验,强调了版本控制、自动化测试等关键点的重要性。
21 5
|
18天前
|
前端开发 Java
学习SpringMVC,建立连接,请求,响应 SpringBoot初学,如何前后端交互(后端版)?最简单的能通过网址访问的后端服务器代码举例
文章介绍了如何使用SpringBoot创建简单的后端服务器来处理HTTP请求,包括建立连接、编写Controller处理请求,并返回响应给前端或网址。
37 0
学习SpringMVC,建立连接,请求,响应 SpringBoot初学,如何前后端交互(后端版)?最简单的能通过网址访问的后端服务器代码举例
|
2天前
|
存储 数据管理 API
零代码能力:轻松搞定表单和API接口,少写80%后端代码,内含资源
小白接口(果创云 YesApi.cn)是一个零代码和低代码开发平台,提供一站式后端云服务,帮助开发者、学生、业余爱好者、工作室、中小企业及无IT技术人员的传统企业快速搭建应用、接口、服务和网站。平台提供500+免费API接口,支持在线API开发、在线表单、数据库管理、图片文件存储、会员管理等功能,无需后端开发经验,轻松实现数据处理和应用开发。
|
1月前
|
SQL JSON Java
springboot 如何编写增删改查后端接口,小白极速入门,附完整代码
本文为Spring Boot增删改查接口的小白入门教程,介绍了项目的构建、配置YML文件、代码编写(包括实体类、Mapper接口、Mapper.xml、Service和Controller)以及使用Postman进行接口测试的方法。同时提供了SQL代码和完整代码的下载链接。
springboot 如何编写增删改查后端接口,小白极速入门,附完整代码
|
1月前
|
存储 NoSQL Java
|
1月前
|
存储 关系型数据库 API
后端开发的艺术:从代码到云部署
在数字时代的浪潮中,后端开发如同一位默默无闻的艺术家,用代码绘制着互联网世界的底层画卷。本文将带你领略后端开发的奥秘,从基础的代码编写到复杂的云部署,每一步都是对技术深度与广度的挑战。我们将一起探索如何在变化莫测的技术海洋中找到自己的北极星,确保项目的成功和职业生涯的发展。无论你是初学者还是资深开发者,这篇文章都将为你提供新的视角和实用的技巧,让你的后端之旅更加精彩。
33 2
|
10天前
|
缓存 Java 数据库
后端技术探索:从基础架构到高效开发的实践之路
【10月更文挑战第7天】 在现代软件开发中,后端技术是支撑应用运行的核心。本文将探讨如何从后端的基础架构出发,通过一系列高效的开发实践,提升系统的性能与可靠性。我们将深入分析后端框架的选择、数据库设计、接口开发等关键领域,并提供实用的代码示例和优化策略,帮助开发者构建更稳定、高效的后端系统。通过这篇文章,读者将获得关于后端开发的全面理解和实践指导,从而更好地应对复杂项目需求。
35 0

热门文章

最新文章