


How does Redis implement verification code sending and limit the number of daily sendings?
1. Function
Enter your mobile phone number, click Send and a six-digit code will be randomly generated, valid for 2 minutes
Enter the verification code , click verification, return success or failure
Each mobile phone number can only be entered 3 times a day
2. Analysis
Each mobile phone can only be entered 3 times a day: after each incr is sent, it is 1. When the value is 3, it prompts that it cannot be sent. The expiration time is the end of the day
Randomly generate a 6-digit verification code: RandomUtil (hutool)
The verification code is valid for 2 minutes: put it in redis and set the expiration time for 2 minutes
Judge whether the verification code is consistent: get the verification code from redis and compare it with the entered verification code
3. Implementation
package cn.ken.blog.controller.common; import cn.hutool.core.date.DateUnit; import cn.hutool.core.date.DateUtil; import cn.hutool.core.util.RandomUtil; import cn.ken.blog.common.constant.Constants; import cn.ken.blog.common.domain.Result; import cn.ken.blog.common.enums.ErrorCodeEnum; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.util.ObjectUtils; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import java.util.Date; import java.util.concurrent.TimeUnit; /** * 验证码控制器 * @author Ken-Chy129 * @date 2022/4/17 20:28 */ @RestController @SuppressWarnings(value = { "unchecked", "rawtypes" }) public class CaptureController { @Autowired private RedisTemplate redisTemplate; // 生成验证码 @GetMapping("getNumCode") public Result<String> getNumCode(String phone) { String captureLimitKey = Constants.CAPTCHA_LIMIT_KEY + phone; Integer counts = (Integer) redisTemplate.opsForValue().get(captureLimitKey); if (ObjectUtils.isEmpty(counts)) { // 今天第一次验证,故之前缓存中无该键 // 距离今天结束剩下多少毫秒 long expire = DateUtil.endOfDay(new Date()).between(new Date(), DateUnit.MS); redisTemplate.opsForValue().set(captureLimitKey, 1, expire, TimeUnit.MILLISECONDS); } else if (counts < 3) { // 没有超过限制次数 redisTemplate.opsForValue().increment(captureLimitKey); } else { // 超过限制次数,不生成验证码,直接返回 return new Result<String>().error(ErrorCodeEnum.OVER_LIMITS); } // 生成验证码 String code = RandomUtil.randomNumbers(6); // 随机生成六位数 String captureCodeKey = Constants.CAPTCHA_CODE_KEY + phone; redisTemplate.opsForValue().set(captureCodeKey, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES); return new Result<String>().success(captureCodeKey + ":" + code); } // 验证验证码 @GetMapping("verify") public Result<String> verify(String phone, String code) { String captureCodeKey = Constants.CAPTCHA_CODE_KEY + phone; String realCode = (String) redisTemplate.opsForValue().get(captureCodeKey); if (ObjectUtils.isEmpty(realCode)) { // redis中不存在该用户生成的验证码,证明验证码以过期销毁 return new Result<String>().error(ErrorCodeEnum.OVERDUE_CODE); } if (realCode.equals(code)) { return new Result<String>().success("验证成功"); } else { return new Result<String>().error(ErrorCodeEnum.ERROR_CODE); } } // @Scheduled(cron = "0 0 12 * * ?") // private void clear() { // redisTemplate.delete() // } }
// Constants类 /** * 验证码 redis key */ public static final String CAPTCHA_CODE_KEY = "captcha_codes:"; /** * 每日限制 redis key */ public static final String CAPTCHA_LIMIT_KEY = "captcha_limits:"; /** * 验证码有效期(分钟) */ public static final Integer CAPTCHA_EXPIRATION = 2;
The above is the detailed content of How does Redis implement verification code sending and limit the number of daily sendings?. For more information, please follow other related articles on the PHP Chinese website!

Redis is a NoSQL database that provides high performance and flexibility. 1) Store data through key-value pairs, suitable for processing large-scale data and high concurrency. 2) Memory storage and single-threaded models ensure fast read and write and atomicity. 3) Use RDB and AOF mechanisms to persist data, supporting high availability and scale-out.

Redis is a memory data structure storage system, mainly used as a database, cache and message broker. Its core features include single-threaded model, I/O multiplexing, persistence mechanism, replication and clustering functions. Redis is commonly used in practical applications for caching, session storage, and message queues. It can significantly improve its performance by selecting the right data structure, using pipelines and transactions, and monitoring and tuning.

The main difference between Redis and SQL databases is that Redis is an in-memory database, suitable for high performance and flexibility requirements; SQL database is a relational database, suitable for complex queries and data consistency requirements. Specifically, 1) Redis provides high-speed data access and caching services, supports multiple data types, suitable for caching and real-time data processing; 2) SQL database manages data through a table structure, supports complex queries and transaction processing, and is suitable for scenarios such as e-commerce and financial systems that require data consistency.

Redisactsasbothadatastoreandaservice.1)Asadatastore,itusesin-memorystorageforfastoperations,supportingvariousdatastructureslikekey-valuepairsandsortedsets.2)Asaservice,itprovidesfunctionalitieslikepub/submessagingandLuascriptingforcomplexoperationsan

Compared with other databases, Redis has the following unique advantages: 1) extremely fast speed, and read and write operations are usually at the microsecond level; 2) supports rich data structures and operations; 3) flexible usage scenarios such as caches, counters and publish subscriptions. When choosing Redis or other databases, it depends on the specific needs and scenarios. Redis performs well in high-performance and low-latency applications.

Redis plays a key role in data storage and management, and has become the core of modern applications through its multiple data structures and persistence mechanisms. 1) Redis supports data structures such as strings, lists, collections, ordered collections and hash tables, and is suitable for cache and complex business logic. 2) Through two persistence methods, RDB and AOF, Redis ensures reliable storage and rapid recovery of data.

Redis is a NoSQL database suitable for efficient storage and access of large-scale data. 1.Redis is an open source memory data structure storage system that supports multiple data structures. 2. It provides extremely fast read and write speeds, suitable for caching, session management, etc. 3.Redis supports persistence and ensures data security through RDB and AOF. 4. Usage examples include basic key-value pair operations and advanced collection deduplication functions. 5. Common errors include connection problems, data type mismatch and memory overflow, so you need to pay attention to debugging. 6. Performance optimization suggestions include selecting the appropriate data structure and setting up memory elimination strategies.

The applications of Redis in the real world include: 1. As a cache system, accelerate database query, 2. To store the session data of web applications, 3. To implement real-time rankings, 4. To simplify message delivery as a message queue. Redis's versatility and high performance make it shine in these scenarios.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver Mac version
Visual web development tools

Notepad++7.3.1
Easy-to-use and free code editor

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool
