200字范文,内容丰富有趣,生活中的好帮手!
200字范文 > Springboot+Redis接入腾讯云短信服务实现验证码发送

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

时间:2019-02-07 12:35:31

相关推荐

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

目录

一、开通腾讯云短信服务

二、代码实现

三、测试

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

一、开通腾讯云短信服务

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

二、代码实现

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

1、通过Maven安装SDK

<dependencies><dependency><groupId>com.tencentcloudapi</groupId><artifactId>tencentcloud-sdk-java</artifactId><!-- go to /search?q=tencentcloud-sdk-java and get the latest version. --><!-- 请到/search?q=tencentcloud-sdk-java查询所有版本,最新版本如下 --><version>3.1.526</version></dependency></dependencies>

2、项目结构

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

3、编写application.properties

3.1 加入腾讯云短信服务相关参数

#腾讯云SMS参数 等号后面替换成自己腾讯云上的参数tencentcloud.sms.secretId=xxxxxxxxxxxxxxxxxxxxtencentcloud.sms.secretKey=xxxxxxxxxxxxxxxxxxxxtencentcloud.sms.sdkAppId=xxxxxxxxxxtencentcloud.sms.signName=xxxxxxxxtencentcloud.sms.templateId=xxxxxxx

3.2 加入Redis相关配置

spring.redis.host=redishostspring.redis.port=6379 spring.redis.database= 0spring.redis.timeout=1800000

4、编写工具类

4.1 Redis配置工具类

@EnableCaching@Configurationpublic class RedisConfig extends CachingConfigurerSupport {@Beanpublic RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {RedisTemplate<String, Object> template = new RedisTemplate<>();RedisSerializer<String> 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;}@Beanpublic CacheManager cacheManager(RedisConnectionFactory factory) {RedisSerializer<String> 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@Datapublic 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;@Overridepublic 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.v0111.xxxx

@Service@Slf4jpublic class SmsServiceImpl implements SmsService {@Autowiredprivate SmsConstantUtils smsConstantUtils;@Overridepublic 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 {/* 必要步骤:* 实例化一个认证对象,入参需要传入腾讯云账户密钥对secretId,secretKey。* 这里采用的是从环境变量读取的方式,需要在环境变量中先设置这两个值。* 你也可以直接在代码中写死密钥对,但是小心不要将代码复制、上传或者分享给他人,* 以免泄露密钥对危及你的财产安全。* SecretId、SecretKey 查询: https://console./cam/capi */Credential cred = new Credential(secretId, secretKey);// 实例化一个http选项,可选,没有特殊需求可以跳过HttpProfile httpProfile = new HttpProfile();// 设置代理(无需要直接忽略)// httpProfile.setProxyHost("真实代理ip");// httpProfile.setProxyPort(真实代理端口);/* SDK默认使用POST方法。* 如果你一定要使用GET方法,可以在这里设置。GET方法无法处理一些较大的请求 */httpProfile.setReqMethod("POST");/* SDK有默认的超时时间,非必要请不要进行调整* 如有需要请在代码中查阅以获取最新的默认值 */httpProfile.setConnTimeout(60);/* 指定接入地域域名,默认就近地域接入域名为 ,也支持指定地域域名访问,例如广州地域的域名为 sms.ap- */httpProfile.setEndpoint("");/* 非必要步骤:* 实例化一个客户端配置对象,可以指定超时时间等配置 */ClientProfile clientProfile = new ClientProfile();/* SDK默认用TC3-HMAC-SHA256进行签名* 非必要请不要修改这个字段 */clientProfile.setSignMethod("HmacSHA256");clientProfile.setHttpProfile(httpProfile);/* 实例化要请求产品(以sms为例)的client对象* 第二个参数是地域信息,可以直接填写字符串ap-guangzhou,支持的地域列表参考 /document/api/382/52071#.E5.9C.B0.E5.9F.9F.E5.88.97.E8.A1.A8 */SmsClient client = new SmsClient(cred, "ap-guangzhou", clientProfile);/* 实例化一个请求对象,根据调用的接口和实际情况,可以进一步设置请求参数* 你可以直接查询SDK源码确定接口有哪些属性可以设置* 属性可能是基本类型,也可能引用了另一个数据结构* 推荐使用IDE进行开发,可以方便的跳转查阅各个接口和数据结构的文档说明 */SendSmsRequest req = new SendSmsRequest();/* 填充请求参数,这里request对象的成员变量即对应接口的入参* 你可以通过官网接口文档或跳转到request对象的定义处查看请求参数的定义* 基本类型的设置:* 帮助链接:* 短信控制台: https://console./smsv2* 腾讯云短信小助手: /document/product/382/3773#.E6.8A.80.E6.9C.AF.E4.BA.A4.E6.B5.81 *//* 短信应用ID: 短信SdkAppId在 [短信控制台] 添加应用后生成的实际SdkAppId,示例如1400006666 */// 应用 ID 可前往 [短信控制台](https://console./smsv2/app-manage) 查看req.setSmsSdkAppId(sdkAppId);/* 短信签名内容: 使用 UTF-8 编码,必须填写已审核通过的签名 */// 签名信息可前往 [国内短信](https://console./smsv2/csms-sign) 或 [国际/港澳台短信](https://console./smsv2/isms-sign) 的签名管理查看req.setSignName(signName);/* 模板 ID: 必须填写已审核通过的模板 ID */// 模板 ID 可前往 [国内短信](https://console./smsv2/csms-template) 或 [国际/港澳台短信](https://console./smsv2/isms-template) 的正文模板管理查看req.setTemplateId(templateId);/* 模板参数: 模板参数的个数需要与 TemplateId 对应模板的变量个数保持一致,若无模板参数,则设置为空 */req.setTemplateParamSet(templateParamSet);/* 下发手机号码,采用 E.164 标准,+[国家或地区码][手机号]* 示例如:+8613711112222, 其中前面有一个+号 ,86为国家码,13711112222为手机号,最多不要超过200个手机号 */req.setPhoneNumberSet(phoneNumberSet);/* 通过 client 对象调用 SendSms 方法发起请求。注意请求方法名与请求对象是对应的* 返回的 res 是一个 SendSmsResponse 类的实例,与请求对象对应 */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 //跨域@Slf4jpublic class SmsController {@Autowiredprivate SmsService smsService;@Autowiredprivate RedisTemplate<String, String> 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中的数据失效

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。