完成短信发送功能
在項目中實現
需要三個步驟:
-  
生成隨機驗證碼
 -  
將驗證碼保存到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
 - 下一篇: 用户注册功能