使用阿里云短信服务发送短信登录验证码
10.1 配置文件# u670Du52A1u7AEFu53E3 server.port=8204 # u670Du52A1u540D spring.application.name=service-msm #u8FD4u56DEjsonu7684u5168u5C40u65F6u95F4u683Cu5F0F spring.jackson.date-format=yyyy-MM-dd HH:mm:ss spring.jackson.time-zone=GMT+8 #Redis配置 spring.redis.host=47.111.149.199 spring.redis.port=6379 spring.redis.password=redis147896325 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 # nacos地址 spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848 #阿里云短信配置 aliyun.sms.regionId=xxxxxxx aliyun.sms.accessKeyId=xxxxxxx aliyun.sms.seceret=xxxxxxxxx #rabbitmqu5730u5740 spring.rabbitmq.host=47.111.149.199 spring.rabbitmq.port=5672 spring.rabbitmq.username=guest spring.rabbitmq.password=guest10.2 启动类
由于发送短信直接使用的是阿里云的api接口,没有用到数据库,因此在启动类上取消数据源的配置。
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)//取消数据源自动配置+
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)//取消数据源自动配置 @EnableDiscoveryClient @ComponentScan(basePackages = {"com.tjj"}) public class ServiceMsmApplication { public static void main(String[] args) { SpringApplication.run(ServiceMsmApplication.class, args); } }10.3 添加配置类
package com.tjj.msm.utils; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Value; public class ConstantPropertiesUtil implements InitializingBean { @Value("$(aliyun.sms.regionId)") private String regionId; @Value("$(aliyun.sms.accessKeyId)") private String accessKeyId; @Value("$(aliyun.sms.secret)") private String secret; public static String REGION_ID; public static String ACCESS_KEY_ID; public static String SECRET; @Override public void afterPropertiesSet() throws Exception { REGION_ID = regionId; ACCESS_KEY_ID = accessKeyId; SECRET = secret; } }10.4 生成四位或六位随机验证码
生成四位或者是六位随机验证码,并将验证码存到redis缓存中,并设置过期时间。如果在有效时间内,则不用重新生成新的验证码,如果验证码没有,则重新生成随机验证码
生成随机验证码工具类:
package com.tjj.msm.utils; 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)); } public static ArrayList getRandom(List list, int n) { Random random = new Random(); HashMap
controller:
@RestController @RequestMapping("/api/msm") public class MsmApiController { @Autowired private MsmService msmService; @Autowired private RedisTemplateredisTemplate; //发送手机验证码 @GetMapping("send/{phone}") public Result sendCode(@PathVariable String phone) { //从redis获取验证码,如果获取获取到,返回ok // key 手机号 value 验证码 String code = redisTemplate.opsForValue().get(phone); if(!StringUtils.isEmpty(code)) { return Result.ok(); } //如果从redis获取不到, // 生成验证码, code = RandomUtil.getSixBitRandom(); //调用service方法,通过整合短信服务进行发送 boolean isSend = msmService.send(phone,code); //生成验证码放到redis里面,设置有效时间 if(isSend) { redisTemplate.opsForValue().set(phone,code,3, TimeUnit.MINUTES); return Result.ok(); } else { return Result.fail().message("发送短信失败"); } } }
在service实现类中实现短信发送:
@Service public class MsmServiceImpl implements MsmService { @Override public boolean send(String phone, String code) { //判断手机号是否为空 if (StringUtils.isEmpty(phone)) { return false; } else { //调用方法进行短信发送 ConstantPropertiesUtils.msmStart(phone, code); return true; } } @Override public boolean send(MsmVo msmVo) { if (!StringUtils.isEmpty(msmVo.getPhone())) { String code = (String) msmVo.getParam().get("code"); ConstantPropertiesUtils.msmStart(msmVo.getPhone(), code); return true; } return false; } }
@Component public class ConstantPropertiesUtils { //省略.... public static void msmStart(String phone, String code) { // 整合容联云短信服务 //生产环境请求地址:app.cloopen.com String serverIp = "app.cloopen.com"; //请求端口 String serverPort = "8883"; //主账号,登陆云通讯网站后,可在控制台首页看到开发者主账号ACCOUNT SID和主账号令牌AUTH TOKEN String accountSId = "8aaf07087ca221d8017cdf63bb460cbd"; // 需修改 String accountToken = "de9326bf81604402ae7a982c0221061a"; // 需修改 //请使用管理控制台中已创建应用的APPID String appId = "8aaf07087ca221d8017cdf63bc320cc4"; // 需修改 CCPRestSmsSDK sdk = new CCPRestSmsSDK(); sdk.init(serverIp, serverPort); sdk.setAccount(accountSId, accountToken); sdk.setAppId(appId); sdk.setBodyType(BodyType.Type_JSON); // 用逗号隔开手机号,官方说最多写三个手机号,似乎能实现群发的效果,但是我没做测试 //String to = "13957757545,17829397989"; String templateId = "1"; // 测试模板写死是1 String[] datas = {code, "3"}; // datas就是发过去短信中的模板,code就是服务端生成的验证码, 3表示几分钟内有效 // 下面这些可选的都不要选,否则会出问题 //String subAppend="1234"; //可选 扩展码,四位数字 0~9999 //String reqId="fadfafas"; //可选 第三方自定义消息id,最大支持32位英文数字,同账号下同一自然天内不允许重复 //HashMap10.4 网关配置result = sdk.sendTemplateSMS(to,templateId,datas); // 这里的phone就是手机号码,我这是方法入参接收的,变量名为phone HashMap result = sdk.sendTemplateSMS(phone, templateId, datas); if ("000000".equals(result.get("statusCode"))) { //正常返回输出data包体信息(map) HashMap data = (HashMap ) result.get("data"); Set keySet = data.keySet(); for (String key : keySet) { Object object = data.get(key); System.out.println(key + " = " + object); } } else { //异常返回输出错误码和错误信息 System.out.println("错误码=" + result.get("statusCode") + " 错误信息= " + result.get("statusMsg")); } } }
在spring-gateway模块中配置网关
spring.cloud.gateway.routes[3].id=service-msm spring.cloud.gateway.routes[3].uri=lb://service-msm spring.cloud.gateway.routes[3].predicates= Path=/*/msm/**11 登录前端页面 11.1 封装api 11.2安装cookie
登陆成功,需要把用户信息存放进cookie里面;命令行执行:
npm install js-cookie11.3 开发前端界面
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)