完成短信发送功能

在项目中实现

需要三个步骤:

  • 生成随机验证码

  • 将验证码保存到Redis中,用来在注册的时候验证

  • 发送验证码到learn-sms-service服务,发送短信

因此,我们需要引入Redis和AMQP:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-amqp</artifactId>
</dependency>

添加RabbitMQ和Redis配置:

spring:
  redis:
    host: 192.168.56.101
  rabbitmq:
    host: 192.168.56.101
    username: learn
    password: learn
    virtual-host: /learn

另外还要用到工具类,生成6位随机码,这个我们封装到了learn-common中,因此需要引入依赖:

<dependency>
    <groupId>com.learn.common</groupId>
    <artifactId>learn-common</artifactId>
    <version>${learn.latest.version}</version>
</dependency>

NumberUtils中有生成随机码的工具方法:

/**
 * 生成指定位数的随机数字
 * @param len 随机数的位数
 * @return 生成的随机数
 */
public static String generateCode(int len){
    len = Math.min(len, 8);
    int min = Double.valueOf(Math.pow(10, len - 1)).intValue();
    int num = new Random().nextInt(
        Double.valueOf(Math.pow(10, len + 1)).intValue() - 1) + min;
    return String.valueOf(num).substring(0,len);
}

UserController

在learn-user-service工程中的UserController添加方法:

/**
 * 发送手机验证码
 * @param phone
 * @return
 */
@PostMapping("code")
public ResponseEntity<Void> sendVerifyCode(String phone) {
    Boolean boo = this.userService.sendVerifyCode(phone);
    if (boo == null || !boo) {
        return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
    }
    return new ResponseEntity<>(HttpStatus.CREATED);
}

UserService

在Service中添加代码:

@Autowired
private StringRedisTemplate redisTemplate;

@Autowired
private AmqpTemplate amqpTemplate;

static final String KEY_PREFIX = "user:code:phone:";

static final Logger logger = LoggerFactory.getLogger(UserService.class);

public Boolean sendVerifyCode(String phone) {
    // 生成验证码
    String code = NumberUtils.generateCode(6);
    try {
        // 发送短信
        Map<String, String> msg = new HashMap<>();
        msg.put("phone", phone);
        msg.put("code", code);
        this.amqpTemplate.convertAndSend("learn.sms.exchange", "sms.verify.code", msg);
        // 将code存入redis
        this.redisTemplate.opsForValue().set(KEY_PREFIX + phone, code, 5, TimeUnit.MINUTES);
        return true;
    } catch (Exception e) {
        logger.error("发送短信失败。phone:{}, code:{}", phone, code);
        return false;
    }
}

注意:要设置短信验证码在Redis的缓存时间为5分钟

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用 Qt 完成验证码功能的代码示例: ```cpp #include <QCoreApplication> #include <QNetworkAccessManager> #include <QNetworkRequest> #include <QNetworkReply> #include <QUrlQuery> #include <QJsonDocument> #include <QJsonObject> #include <QJsonValue> #include <QTimer> #include <QDebug> class SmsVerification : public QObject { Q_OBJECT public: SmsVerification(QObject *parent = nullptr) : QObject(parent) { // 初始化网络访问管理器 m_networkManager = new QNetworkAccessManager(this); // 设置验证码有效期为 60 秒 m_verificationCodeTimeout = 60; } // 获取验证码 void getVerificationCode(const QString &phoneNumber) { // 构造请求 URL QUrl url("https://api.example.com/verification_code"); QUrlQuery urlQuery; urlQuery.addQueryItem("phone_number", phoneNumber); url.setQuery(urlQuery); // 发送 GET 请求 QNetworkRequest request(url); QNetworkReply *reply = m_networkManager->get(request); // 接收响应 connect(reply, &QNetworkReply::finished, this, [=]() { if (reply->error() == QNetworkReply::NoError) { // 解析响应 JSON QJsonDocument jsonDocument = QJsonDocument::fromJson(reply->readAll()); QJsonObject jsonObject = jsonDocument.object(); QString verificationCode = jsonObject.value("verification_code").toString(); // 发送验证码到手机 sendVerificationCode(phoneNumber, verificationCode); // 设置验证码超时定时器 QTimer::singleShot(m_verificationCodeTimeout * 1000, [=]() { emit verificationCodeTimeout(); }); } else { // 发送错误号 emit getVerificationCodeFailed(reply->errorString()); } // 删除响应对象 reply->deleteLater(); }); } signals: // 获取验证码失败号 void getVerificationCodeFailed(const QString &errorMessage); // 验证码超时号 void verificationCodeTimeout(); private: // 发送验证码到手机 void sendVerificationCode(const QString &phoneNumber, const QString &verificationCode) { // TODO: 发送验证码到手机 qDebug() << "Verification code sent to" << phoneNumber << ":" << verificationCode; } private: QNetworkAccessManager *m_networkManager; // 网络访问管理器 int m_verificationCodeTimeout; // 验证码超时时间(秒) }; int main(int argc, char *argv[]) { QCoreApplication app(argc, argv); SmsVerification smsVerification; // 获取验证码 smsVerification.getVerificationCode("13812345678"); // 处理获取验证码失败号 QObject::connect(&smsVerification, &SmsVerification::getVerificationCodeFailed, &app, [](const QString &errorMessage) { qDebug() << "Failed to get verification code:" << errorMessage; app.quit(); }); // 处理验证码超时号 QObject::connect(&smsVerification, &SmsVerification::verificationCodeTimeout, &app, []() { qDebug() << "Verification code timeout"; app.quit(); }); return app.exec(); } #include "main.moc" ``` 以上代码中,`SmsVerification` 类封装了获取验证码的功能,使用 `getVerificationCode` 方法可以向指定的手机号码发送验证码。该方法会先向服务器发送 GET 请求获取验证码,然后发送验证码到手机,并设置验证码超时定时器。在验证码超时后,将会发出 `verificationCodeTimeout` 号。 使用时,只需创建 `SmsVerification` 对象并调用 `getVerificationCode` 方法即可。代码中还处理了获取验证码失败和验证码超时的情况,可以根据实际需求进行适当修改。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值