栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Springboot+Redis接入腾讯云短信服务实现验证码发送

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Springboot+Redis接入腾讯云短信服务实现验证码发送

目录

一、开通腾讯云短信服务

二、代码实现

三、测试   


  申请阿里云短信服务需要以上线APP或已备案网站,腾讯云短信服务可以使用微信公众号申请,注册个人微信公众号比较方便,改用腾讯云短信服务,参考官方SDK文档实现验证码发送微服务模块。

一、开通腾讯云短信服务

具体流程在之前的博客:腾讯云短信服务申请+测试

二、代码实现

官方SDK文档 短信 Java SDK-SDK 文档-文档中心-腾讯云-腾讯云 (tencent.com)

1、通过Maven安装SDK
 
        
            com.tencentcloudapi
            tencentcloud-sdk-java
            
            
            3.1.526
        
    

2、项目结构

微服务在线教育项目的其中一个模块用到短信验证,部分结构如图所示

3、编写application.properties

3.1 加入腾讯云短信服务相关参数
#腾讯云SMS参数 等号后面替换成自己腾讯云上的参数
tencentcloud.sms.secretId=xxxxxxxxxxxxxxxxxxxx
tencentcloud.sms.secretKey=xxxxxxxxxxxxxxxxxxxx
tencentcloud.sms.sdkAppId=xxxxxxxxxx
tencentcloud.sms.signName=xxxxxxxx
tencentcloud.sms.templateId=xxxxxxx

3.2 加入Redis相关配置
spring.redis.host=redishost
spring.redis.port=6379 
spring.redis.database= 0
spring.redis.timeout=1800000

4、编写工具类

4.1 Redis配置工具类
@EnableCaching
@Configuration
public class RedisConfig extends CachingConfigurerSupport {

    @Bean
    public RedisTemplate redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate template = new RedisTemplate<>();
        RedisSerializer redisSerializer = new StringRedisSerializer();
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        template.setConnectionFactory(factory);
        //key序列化方式
        template.setKeySerializer(redisSerializer);
        //value序列化
        template.setValueSerializer(jackson2JsonRedisSerializer);
        //value hashmap序列化
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        return template;
    }

    @Bean
    public CacheManager cacheManager(RedisConnectionFactory factory) {
        RedisSerializer redisSerializer = new StringRedisSerializer();
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        //解决查询缓存转换异常的问题
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        // 配置序列化(解决乱码的问题),过期时间600秒
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofSeconds(600))
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
                .disableCachingNullValues();
        RedisCacheManager cacheManager = RedisCacheManager.builder(factory)
                .cacheDefaults(config)
                .build();
        return cacheManager;
    }
}

4.2 获取随机数
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("000000");

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

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

4.3 读取配置文件中的内容
@Component
@Data
public class SmsConstantUtils implements InitializingBean {

    //读取配置文件内容
    @Value("${tencentcloud.sms.secretId}")
    private String secretId;

    @Value("${tencentcloud.sms.secretKey}")
    private String secretKey;

    @Value("${tencentcloud.sms.sdkAppId}")
    private String sdkAppId;

    @Value("${tencentcloud.sms.signName}")
    private String signName;

    @Value("${tencentcloud.sms.templateId}")
    private String templateId;

    //定义公开静态常量
    public static String SECRET_ID;
    public static String SECRET_KEY;
    public static String SDKAPP_ID;
    public static String SIGN_NAME;
    public static String TEMPLATED_ID;

    @Override
    public void afterPropertiesSet() throws Exception {
        SECRET_ID=secretId;
        SECRET_KEY=secretKey;
        SDKAPP_ID=sdkAppId;
        SIGN_NAME=signName;
        TEMPLATED_ID=templateId;
    }
}

5、接口SmsService
public interface SmsService {

    boolean send(String phone, String param);
}

6、实现类SmsServiceImpl

注意: 这里导入腾讯云api的版本都是 com.tencentcloudapi.sms.v20210111.xxxx 

@Service
@Slf4j
public class SmsServiceImpl implements SmsService {

    @Autowired
    private SmsConstantUtils smsConstantUtils;

    @Override
    public boolean send(String phone, String param) {
        String phoneNumber = "+86" + phone;
        String secretId = smsConstantUtils.getSecretId();
        String secretKey = smsConstantUtils.getSecretKey();
        String sdkAppId = smsConstantUtils.getSdkAppId();
        String signName = smsConstantUtils.getSignName();
        String templateId = smsConstantUtils.getTemplateId();

        String[] phoneNumberSet = {phoneNumber};
        String[] templateParamSet = {param.toString()};//对应模板中{1}
        try {
            
            Credential cred = new Credential(secretId, secretKey);

            // 实例化一个http选项,可选,没有特殊需求可以跳过
            HttpProfile httpProfile = new HttpProfile();
            // 设置代理(无需要直接忽略)
            // httpProfile.setProxyHost("真实代理ip");
            // httpProfile.setProxyPort(真实代理端口);
            
            httpProfile.setReqMethod("POST");
            
            httpProfile.setConnTimeout(60);
            
            httpProfile.setEndpoint("sms.tencentcloudapi.com");

            
            ClientProfile clientProfile = new ClientProfile();
            
            clientProfile.setSignMethod("HmacSHA256");
            clientProfile.setHttpProfile(httpProfile);
            
            SmsClient client = new SmsClient(cred, "ap-guangzhou", clientProfile);
            
            SendSmsRequest req = new SendSmsRequest();

            

            
            // 应用 ID 可前往 [短信控制台](https://console.cloud.tencent.com/smsv2/app-manage) 查看
            req.setSmsSdkAppId(sdkAppId);

            
            // 签名信息可前往 [国内短信](https://console.cloud.tencent.com/smsv2/csms-sign) 或 [国际/港澳台短信](https://console.cloud.tencent.com/smsv2/isms-sign) 的签名管理查看
            req.setSignName(signName);

            
            // 模板 ID 可前往 [国内短信](https://console.cloud.tencent.com/smsv2/csms-template) 或 [国际/港澳台短信](https://console.cloud.tencent.com/smsv2/isms-template) 的正文模板管理查看
            req.setTemplateId(templateId);

            
            req.setTemplateParamSet(templateParamSet);

            
            req.setPhoneNumberSet(phoneNumberSet);

            
            SendSmsResponse res = client.SendSms(req);
            //获取响应结果
            SendStatus[] sendStatusSet = res.getSendStatusSet();
            // 输出json格式的字符串回包
            System.out.println(SendSmsResponse.toJsonString(res));
            log.info("短信发送返回的响应:"+sendStatusSet);
            return true;
        } catch (TencentCloudSDKException e) {
            log.error("腾讯云短信发送sdk调用失败:"+e.getErrorCode()+","+e.getMessage());
            return false;
        }
    }
}

6、Controller
@RestController
@Api(description = "腾讯云短信服务")
@RequestMapping("/edusms/sms")
@CrossOrigin //跨域
@Slf4j
public class SmsController {

    @Autowired
    private SmsService smsService;

    @Autowired
    private RedisTemplate redisTemplate;

    @ApiOperation("发送短信")
    @GetMapping(value = "/send/{phone}")
    public R code(@PathVariable String phone) {
        String code = redisTemplate.opsForValue().get(phone);
        if(!StringUtils.isEmpty(code)) return R.ok();

        String Vcode = RandomUtil.getSixBitRandom();
        boolean isSend = smsService.send(phone, Vcode);
        if(isSend) {
            //验证码5分钟失效
            redisTemplate.opsForValue().set(phone, Vcode,5,TimeUnit.MINUTES);
            return R.ok();
        } else {
            return R.error().message("发送短信失败");
        }
    }
}

三、测试

使用Swagger进行测试 http://localhost:8005/swagger-ui.html

控制台输出

Redis中的数据

收到短信

五分钟后Redis中的数据失效 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/969819.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号