1.环境搭建
-
新建auth模块
-
host注册auth.dreammall.com域名
-
静态资源上传nginx
-
网关yml配置
-
修改hmtl页面
-
页面效果
-
修改商城首页的跳转路径到auth服务
2.整合短信发送服务
-
因为是个人练习并且阿里云发短信需要认证比较麻烦,所以使用了免费的15条短信,短信发送完之后可以发送到邮箱继续测试。
-
阿里云链接地址 阿里云->云市场->三网短信认证
https://market.aliyun.com/products/57124001/cmapi00037170.html?spm=5176.product-detail.detail.4.20107b9dN0PjJb&accounttraceid=ced5a67c087a404dafca773fa4ac5de2gvzd
// 在第三服务模块写的,其它服务模块需要使用通过openfeign调用即可。 @Configuration @ConfigurationProperties(prefix = "spring.cloud.alicloud.sms") public class SmsComponent { @Setter private String host; @Setter private String path; @Setter private String appcode; @Setter private String templateId; /** * @param phone 手机号码 * @param code 验证码 */ public void sendCode(String phone, String code) { String method = "POST"; Map<String, String> headers = new HashMap<>(); //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105 headers.put("Authorization", "APPCODE " + appcode); //根据API的要求,定义相对应的Content-Type headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); Map<String, String> querys = new HashMap<>(); Map<String, String> bodys = new HashMap<>(); bodys.put("content", "code:"+code); bodys.put("phone_number", phone); bodys.put("template_id", templateId); try { HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys); System.out.println(response.toString()); //获取response的body } catch (Exception e) { e.printStackTrace(); } } }
// controller层 @RestController @RequestMapping("/sms") public class SendSmsPartyController { @Autowired private SmsComponent smsComponent; @RequestMapping("/sendCode") public R sendCode(@RequestParam("phone") String phone,@RequestParam("code") String code) { try { smsComponent.sendCode(phone,code); return R.ok(); } catch (Exception e) { return R.error("发送短信时出现异常"); } } }
@ResponseBody
@GetMapping(value = "/sms/sendCode")
public R sendCode(@RequestParam("phone") String phone) {
//1、接口防刷
//活动存入redis的时间,用当前时间减去存入redis的时间,判断用户手机号是否在60s内发送验证码
String cacheCode = stringRedisTemplate.opsForValue().get(AuthConstant.SMS_CODE_CACHE_PREFIX + phone);
if (StrUtil.isNotBlank(cacheCode)) {
//60s内不能再发 1666971300839 1666971300900
long parseLong = Long.parseLong(cacheCode.split("_")[1]);
if (System.currentTimeMillis() - parseLong < 60000) {
return R.error(BizCodeEnum.SMS_CODE_EXCEPTION.getCode(), BizCodeEnum.SMS_CODE_EXCEPTION.getMsg());
}
}
//2、验证码的再次效验 redis.存key-phone,value-code
int code = (int) ((Math.random() * 9 + 1) * 100000);
String codeNum = String.valueOf(code);
String redisStorage = codeNum + "_" + System.currentTimeMillis();
try {
R r = sendSmsPartyFeignService.sendCode(phone, codeNum);
if (r.get("code").equals(0)) {
//存入redis,防止同一个手机号在60秒内再次发送验证码
stringRedisTemplate.opsForValue().set(AuthConstant.SMS_CODE_CACHE_PREFIX + phone, redisStorage, 10, TimeUnit.MINUTES);
}
return R.ok();
} catch (Exception e) {
return R.error(BizCodeEnum.SEND_SMS_CODE_EXCEPTION.getCode(), BizCodeEnum.SEND_SMS_CODE_EXCEPTION.getMsg());
}
}