当前位置:
首页 >
完成短信发送功能
发布时间:2024/4/13
46
豆豆
在项目中实现
需要三个步骤:
-
生成随机验证码
-
将验证码保存到Redis中,用来在注册的时候验证
-
发送验证码到learn-sms-service服务,发送短信
因此,我们需要引入Redis和AMQP:
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-amqp</artifactId> </dependency>添加RabbitMQ和Redis配置:
spring:redis:host: 192.168.56.101rabbitmq:host: 192.168.56.101username: learnpassword: learnvirtual-host: /learn另外还要用到工具类,生成6位随机码,这个我们封装到了learn-common中,因此需要引入依赖:
<dependency><groupId>com.learn.common</groupId><artifactId>learn-common</artifactId><version>${learn.latest.version}</version> </dependency>NumberUtils中有生成随机码的工具方法:
/*** 生成指定位数的随机数字* @param len 随机数的位数* @return 生成的随机数*/ public static String generateCode(int len){len = Math.min(len, 8);int min = Double.valueOf(Math.pow(10, len - 1)).intValue();int num = new Random().nextInt(Double.valueOf(Math.pow(10, len + 1)).intValue() - 1) + min;return String.valueOf(num).substring(0,len); }UserController
在learn-user-service工程中的UserController添加方法:
/*** 发送手机验证码* @param phone* @return*/ @PostMapping("code") public ResponseEntity<Void> sendVerifyCode(String phone) {Boolean boo = this.userService.sendVerifyCode(phone);if (boo == null || !boo) {return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);}return new ResponseEntity<>(HttpStatus.CREATED); }UserService
在Service中添加代码:
@Autowired private StringRedisTemplate redisTemplate;@Autowired private AmqpTemplate amqpTemplate;static final String KEY_PREFIX = "user:code:phone:";static final Logger logger = LoggerFactory.getLogger(UserService.class);public Boolean sendVerifyCode(String phone) {// 生成验证码String code = NumberUtils.generateCode(6);try {// 发送短信Map<String, String> msg = new HashMap<>();msg.put("phone", phone);msg.put("code", code);this.amqpTemplate.convertAndSend("learn.sms.exchange", "sms.verify.code", msg);// 将code存入redisthis.redisTemplate.opsForValue().set(KEY_PREFIX + phone, code, 5, TimeUnit.MINUTES);return true;} catch (Exception e) {logger.error("发送短信失败。phone:{}, code:{}", phone, code);return false;} }注意:要设置短信验证码在Redis的缓存时间为5分钟
总结
- 上一篇: redis的安装及springDataR
- 下一篇: 用户注册功能