Redis實現短信驗證碼登錄的示例代碼

效果圖

發送驗證碼

輸入手機號、密碼以及驗證碼完成登錄操作

pom.xml

核心依賴

<dependencies>
    <dependency>
        <groupId>cn.hutool</groupId>
        <artifactId>hutool-all</artifactId>
        <version>5.7.22</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-pool2</artifactId>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.47</version>
    </dependency>
    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>2.2.2</version>
    </dependency>
</dependencies>

applicatoin.yml

server:
  port: 8080

spring:
  application:
    name: redis-lettuce
  datasource:
    url: jdbc:mysql://aliyun-rds.mysql.rds.aliyuncs.com/illness?useSSL=false
    username: root
    password: 123456
    driver-class-name: com.mysql.jdbc.Driver
    # useSSL : 一般通過證書或者令牌進行安全認證,否則通過賬號和密碼進行連接
  redis:
    database: 0  #Redis索引0~15,默認為0
    host: ip
    port: 6379
    password: 123456 #密碼(默認為空)
    lettuce: # 這裡標明使用lettuce配置
      pool:
        max-active: 8   #連接池最大連接數(使用負值表示沒有限制)
        max-wait: -1ms  #連接池最大阻塞等待時間(使用負值表示沒有限制)
        max-idle: 5     #連接池中的最大空閑連接
        min-idle: 0     #連接池中的最小空閑連接
    timeout: 10000ms    #連接超時時間(毫秒)

Redis配置類

/**
 * Redis配置類
 *
 * @author issavior
 */
@Configuration
public class RedisConf {

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {


        // 創建Template
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        // 設置連接工廠
        redisTemplate.setConnectionFactory(redisConnectionFactory);

        // 設置序列化工具
        GenericJackson2JsonRedisSerializer jsonRedisSerializer = new GenericJackson2JsonRedisSerializer();

        // key和 hashKey采用 string序列化
        redisTemplate.setKeySerializer(RedisSerializer.string());
        redisTemplate.setHashKeySerializer(RedisSerializer.string());

        // value和 hashValue采用 JSON序列化
        redisTemplate.setValueSerializer(jsonRedisSerializer);
        redisTemplate.setHashValueSerializer(jsonRedisSerializer);

        return redisTemplate;
    }
}

controller

/**
 * @author issavior
 */
@RestController
@RequestMapping("/user")
public class UserController {

    /**
     * userService
     */
    @Autowired
    private UserService userService;

    /**
     * 登錄
     *
     * @param issa issa
     * @return ResponseEntity<Issa>
     */
    @PostMapping("/login")
    public ResponseEntity<Object> login(@RequestBody Issa issa) {

        return userService.login(issa);

    }

    /**
     * 獲取驗證碼
     *
     * @param phone phone
     * @return ResponseEntity<Object>
     */
    @GetMapping("/{phone}")
    public ResponseEntity<Object> verificationCode(@PathVariable String phone) {

        return ResponseEntity.ok(userService.verificationCode(phone));
    }


    /**
     * 註冊
     *
     * @param issa issa
     * @return ResponseEntity<Object>
     */
    @PostMapping
    public ResponseEntity<Object> register(@RequestBody Issa issa) {

        issa.setId(UUID.randomUUID().toString(true));

        return userService.register(issa);

    }

serviceImpl

/**
 * @author issavior
 */
@Service
@Slf4j
public class UserServiceImpl implements UserService {

    /**
     * redisTemplate
     */
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * userMapper
     */
    @Autowired
    private UserMapper userMapper;

    /**
     * 登錄
     *
     * @param issa 登錄的參數
     * @return ResponseEntity<Object>
     */
    @Override
    public ResponseEntity<Object> login(Issa issa) {

        Issa user = userMapper.getUser(issa);

        if (user == null) {
            return ResponseEntity.status(400).body("手機號或密碼錯誤");
        }

        String phone = issa.getPhone();

        String verificationCode = (String) redisTemplate.opsForValue().get("login:" + phone);

        String verifyCode = issa.getVerifyCode();
        if (!Objects.equals(verifyCode, verificationCode)) {
            return ResponseEntity.status(400).body("請輸入正確的驗證碼");
        }

        return ResponseEntity.ok("登錄成功");
    }

    /**
     * 註冊
     *
     * @param issa 註冊的參數
     * @return ResponseEntity<Object>
     */
    @Override
    public ResponseEntity<Object> register(Issa issa) {

        int user = userMapper.insertUser(issa);

        if (user != 1) {
            return ResponseEntity.status(400).body("註冊失敗");
        }

        return ResponseEntity.ok("註冊成功");
    }

    /**
     * 獲取驗證碼
     *
     * @param phone 手機號
     * @return Object
     */
    @Override
    public Object verificationCode(String phone) {

        String randomCode = RandomUtil.randomNumbers(6);

        redisTemplate.opsForValue().set("login:" + phone, randomCode);
        log.info("驗證碼已經存入進redis服務器中:" + randomCode);

        String code = (String) redisTemplate.opsForValue().get("login:" + phone);
        if (code == null) {
            return "驗證碼獲取失敗";
        }

        return "驗證碼獲取成功【 " + code + " 】";


    }
}

mapper

/**
 * @author issavior
 */
public interface UserMapper {

    /**
     * 新增用戶&註冊
     *
     * @param issa 參數
     * @return int:新增成功返回1,否則返回0
     */
    @Insert("insert into issa(id,user_name,password,nick_name,sex,age,phone) values (#{id},#{userName},#{password},#{nickName},#{sex},#{age},#{phone})")
    int insertUser(Issa issa);

    /**
     * 用於登錄時,根據手機號和密碼判斷是否有相關用戶
     *
     * @param issa issa
     * @return int
     */
    @Select("select * from issa where phone = #{phone} and password = #{password}")
    Issa getUser(Issa issa);
}

以上就是Redis實現短信驗證碼登錄的示例代碼的詳細內容,更多關於Redis短信驗證碼登錄的資料請關註WalkonNet其它相關文章!

推薦閱讀: