首頁 > 軟體

Redis實現簡訊驗證碼登入的範例程式碼

2022-06-13 18:01:24

效果圖

傳送驗證碼

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

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簡訊驗證碼登入的資料請關注it145.com其它相關文章!


IT145.com E-mail:sddin#qq.com