ARTICLE DETAIL

建站实战干货

来自一线的建站与推广经验沉淀,每一条都经过真实交付验证。

集成SpringCloudAlibaba短信服务 短信验证码

2026/8/13 9:56:24 拓冰建站 浏览量
集成SpringCloudAlibaba短信服务 短信验证码

1.1 SpringCloudAlibaba短信服务简介

短信服务(Short Message Service)是阿里云为用户提供的一种通信服务的能力。

  • 产品优势:覆盖全面、高并发处理、消息堆积处理、开发管理简单、智能监控调度

  • 产品功能:短信通知、短信验证码、推广短信、异步通知、数据统计

  • 应用场景:短信验证码、系统信息推送、推广短信等

SpringCloudAlibaba提供的短信服务,集成更加方便,代码更加简洁。

1.2 代码解析

1.2.1 基本配置与工具类封装

(1)我们这里使用了SpringCloudAlibaba中提供的短信服务

工程引入依赖

<dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-alicloud-sms</artifactId><version>2.2.0.RELEASE</version>
</dependency>

(2)配置文件添加短信相关的配置,密钥的配置

spring:cloud:alicloud:access-key: XXXsecret-key: XXX

以及签名和模板号的配置(自定义)

sms:operator:signName: xxxtemplateCode: xxx

(3)SmsConfig用于读取配置文件中的签名和模板编号

package com.lkd.sms;
​
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
​
@Configuration
public class SmsConfig {@Value("${sms.operator.signName}")private String signName;@Value("${sms.operator.templateCode}")private String templateCode;
​public String getSignName() {return signName;}
​public String getTemplateCode() {return templateCode;}
}

(4)SmsSender用于封装发送短信的方法

package com.lkd.sms;
​
import com.alibaba.alicloud.sms.ISmsService;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
​
@Component
@Slf4j
public class SmsSender {@Autowiredprivate SmsConfig smsConfig;@Autowiredprivate ISmsService smsService;
​/***  发送验证码短信* @param telphone 手机号* @param code 手机验证码*/public void sendMsg(String telphone,String code){// 组装请求对象-具体描述见控制台-文档部分内容SendSmsRequest request = new SendSmsRequest();
​// 必填:待发送手机号request.setPhoneNumbers(telphone);// 必填:短信签名-可在短信控制台中找到request.setSignName(smsConfig.getSignName());// 必填:短信模板-可在短信控制台中找到request.setTemplateCode(smsConfig.getTemplateCode());// 可选:模板中的变量替换JSON串,如模板内容为"【企业级分布式应用服务】,您的验证码为${code}"时,此处的值为ObjectMapper mapper = new ObjectMapper();JsonNode rootNode = mapper.createObjectNode();((ObjectNode)rootNode).put("code",code);try {request.setTemplateParam(mapper.writeValueAsString(rootNode));//{"code":code}smsService.sendSmsRequest(request);}catch (Exception e) {log.error("send sms error.",e);}}
}

在需要发送短信的地方,直接引入SmsSender即可

1.2.2 发送短信验证码

(1)发送短信验证码, UserService定义方法

/*** 发送验证码* @param mobile*/
void sendCode(String mobile);

UserServiceImpl实现方法

@Autowired
private SmsSender smsSender;
​
@Override
public void sendCode(String mobile){if(Strings.isNullOrEmpty(mobile)) return;LambdaQueryWrapper<UserEntity> wrapper = new LambdaQueryWrapper<>();wrapper.eq(UserEntity::getMobile,mobile);if(this.count(wrapper)<=0) return;if(redisTemplate.opsForValue().get(mobile) != null) return;//生成5位验证码StringBuilder sbCode = new StringBuilder();Stream.generate( ()-> new Random().nextInt(10)).limit(5).forEach(x-> sbCode.append(x));redisTemplate.opsForValue().set(mobile,sbCode.toString(), Duration.ofMinutes(5));smsSender.sendMsg(mobile,sbCode.toString());
}

(2)UserController新增方法

/*** 生成登录手机验证码* @param mobile*/
@GetMapping("/code/{mobile}")
public void generateCode(@PathVariable String mobile){userService.sendCode(mobile);
}