腾讯云短信代码参考

尚硅谷的项目,没有做radis缓存

目录结构

在这里插入图片描述

MsmController

package com.atguigu.msmservice.controller;

import com.atguigu.commonutils.R;


import com.atguigu.msmservice.service.MsmService;
import io.swagger.annotations.ApiParam;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/edumsm/msm")
@CrossOrigin
public class MsmController {
    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    //发送短信的方法
    @GetMapping("send/{phone}")
    public R sendMsm(@ApiParam(name = "phone",value = "手机号码",required = true)
                         @PathVariable String phone) {
        //调用service发送短信的方法
        boolean isSend = msmService.send(phone);
        if (isSend){
            return R.ok();
        }else {
            return R.error().message("短信发送失败!");
        }
    }
}

MsmService

@Service
public interface MsmService {
    boolean send(String phone);
}

MsmServiceImpl

package com.atguigu.msmservice.service.impl;

import com.atguigu.msmservice.service.MsmService;

import java.util.Map;

import com.atguigu.msmservice.utils.ConstantSmsUtils;
import com.atguigu.msmservice.utils.RandomUtil;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.sms.v20210111.SmsClient;
import com.tencentcloudapi.sms.v20210111.models.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

@Service
public class MsmServiceImpl implements MsmService {
    @Override
    public boolean send(String phone) {
        //判断手机号是否为空
        if (StringUtils.isEmpty(phone)){
            return false;
        }
        try{
            // 实例化一个认证对象,入参需要传入腾讯云账户secretId,secretKey,此处还需注意密钥对的保密
            // 密钥可前往https://console.cloud.tencent.com/cam/capi网站进行获取
            Credential cred = new Credential(ConstantSmsUtils.SECRET_ID, ConstantSmsUtils.SECRET_KEY);
            // 实例化一个http选项,可选的,没有特殊需求可以跳过
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("sms.tencentcloudapi.com");
            // 实例化一个client选项,可选的,没有特殊需求可以跳过
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);
            // 实例化要请求产品的client对象,clientProfile是可选的  第二个参数是地域信息
            SmsClient client = new SmsClient(cred, "ap-guangzhou", clientProfile);
            // 实例化一个请求对象,每个接口都会对应一个request对象
            SendSmsRequest req = new SendSmsRequest();
            //设置固定的参数
            req.setSmsSdkAppId(ConstantSmsUtils.SMSSDKAPP_ID);// 短信应用ID: 短信SdkAppId在 [短信控制台] 添加应用后生成的实际SdkAppId
            req.setSignName(ConstantSmsUtils.SIGN_NAME);//短信签名内容: 使用 UTF-8 编码,必须填写已审核通过的签名
            req.setTemplateId(ConstantSmsUtils.TEMPLATE_ID);//模板 ID: 必须填写已审核通过的模板 ID
            /* 用户的 session 内容: 可以携带用户侧 ID 等上下文信息,server 会原样返回 */
//            String sessionContext = "xxx";
//            req.setSessionContext(sessionContext);

            //设置发送相关的参数
            String[] phoneNumberSet1 = {"86"+phone};
            req.setPhoneNumberSet(phoneNumberSet1);//发送的手机号
            //生成6位数随机验证码
            String verificationCode = RandomUtil.getSixBitRandom();
            String[] templateParamSet1 = {verificationCode};//模板的参数 第一个是验证码,第二个是过期时间
            req.setTemplateParamSet(templateParamSet1);//发送验证码

            //发送短信
            // 返回的resp是一个SendSmsResponse的实例,与请求对象对应
            SendSmsResponse resp = client.SendSms(req);
            System.out.println("resp"+resp);
            // 输出json格式的字符串回包
            System.out.println(SendSmsResponse.toJsonString(resp));
            return true;
        } catch (TencentCloudSDKException e) {
            e.printStackTrace();
            return false;
        }
    }

}

ConstantSmsUtils

package com.atguigu.msmservice.utils;



import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * 实现了InitializingBean接口,当spring进行初始化bean时,会执行afterPropertiesSet方法
 */
@Component
public class ConstantSmsUtils implements InitializingBean {
    @Value("${tencent.sms.keyId}")
    private String secretID ;
    @Value("${tencent.sms.keysecret}")
    private String secretKey ;
    @Value("${tencent.sms.smsSdkAppId}")
    private String smsSdkAppID ;
    @Value("${tencent.sms.signName}")
    private String signName ;
    @Value("${tencent.sms.templateId}")
    private String templateID ;

    public static String SECRET_ID;
    public static String SECRET_KEY;
    public static String SMSSDKAPP_ID;
    public static String SIGN_NAME;
    public static String TEMPLATE_ID;


    @Override
    public void afterPropertiesSet() throws Exception {
        SECRET_ID = secretID;
        SECRET_KEY = secretKey;
        SMSSDKAPP_ID = smsSdkAppID;
        SIGN_NAME = signName;
        TEMPLATE_ID = templateID;
    }
}

RandomUtil

package com.atguigu.msmservice.utils;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;

/**
 * 获取随机数
 *
 * @author qianyi
 *
 */
public class RandomUtil {

    private static final Random random = new Random();

    private static final DecimalFormat fourdf = new DecimalFormat("0000");

    private static final DecimalFormat sixdf = new DecimalFormat("0000");

    public static String getFourBitRandom() {
        return fourdf.format(random.nextInt(10000));
    }

    public static String getSixBitRandom() {
        return sixdf.format(random.nextInt(1000000));
    }

    /**
     * 给定数组,抽取n个数据
     * @param list
     * @param n
     * @return
     */
    public static ArrayList getRandom(List list, int n) {

        Random random = new Random();

        HashMap<Object, Object> hashMap = new HashMap<Object, Object>();

        // 生成随机数字并存入HashMap
        for (int i = 0; i < list.size(); i++) {

            int number = random.nextInt(100) + 1;

            hashMap.put(number, i);
        }

        // 从HashMap导入数组
        Object[] robjs = hashMap.values().toArray();

        ArrayList r = new ArrayList();

        // 遍历数组并打印数据
        for (int i = 0; i < n; i++) {
            r.add(list.get((int) robjs[i]));
            System.out.print(list.get((int) robjs[i]) + "\t");
        }
        System.out.print("\n");
        return r;
    }
}

application.properties

tencent.sms.keyId= AKID3zkMm8LMAm9MvIUTVI1e3EAvVKuKXVFk
tencent.sms.keysecret=MTO9h1SkqkS2QaXJyXxQn0zwmTySo4De
tencent.sms.smsSdkAppId=改成自己的
tencent.sms.signName=改成自己的
tencent.sms.templateId=改成自己的
server.port=8005
spring.application.name=service-msm
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/数据库名称改成自己的?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=root
spring.redis.host=192.168.44.132
spring.redis.port=6379
spring.redis.database= 0
spring.redis.timeout=1800000
spring.redis.lettuce.pool.max-active=20
spring.redis.lettuce.pool.max-wait=-1
spring.redis.lettuce.pool.max-idle=5
spring.redis.lettuce.pool.min-idle=0
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
spring.jackson.time-zone=GMT+8
spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848
#mybatis???
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值