1. Problems with single-point Redis
1. Data loss problem
Redis data persistence.
2. Concurrency issue
Our master-slave cluster realizes the separation of reading and writing.
3. Failure recovery issues
Use Redis Sentinel to implement health detection and automatic recovery.
4. Storage capacity issue
Build a sharded cluster and use the slot mechanism to achieve dynamic expansion.
2. RDB
RDB's full name is Redis Database Backup file (Redis data backup file), also called Redis data snapshot. To put it simply, all the data in the memory is recorded to the disk. When the Redis instance fails and restarts, the snapshot file is read from the disk and the data is restored.
The snapshot file is called an RDB file and is saved in the current running directory by default.
There is a mechanism to trigger RDB inside Redis, which can be found in the redis.conf file. The format is as follows:
When the bgsave command is executed, fork will be passed. The system call creates a child process that shares memory data with the main process. After completing the fork, read the memory data and write it to the RDB file.
Fork uses copy-on-write technology:
When the main process performs a read operation, it accesses the shared memory;
When the main process performs a write operation, it will copy a copy of the data and perform the write operation;
The basic process of RDB mode bgsave?
Fork the main process to get a child process and share the memory space;
The child process reads the memory data and writes a new RDB file;
Replace the old RDB file with the new RDB file;
When will RDB be executed? What does save 60 1000 mean?
The default is when the service is stopped;
means that RDB will be triggered if at least 1000 modifications are performed within 60 seconds;
Disadvantages of RDB?
The RDB execution interval is long, and there is a risk of data loss between two RDB writes;
fork sub-process, compression, write It is time-consuming to export RDB files;
The frequency of AOF command recording can also be configured through the redis.conf file:
3. AOF
AOF stands for Append Only File. Every write command processed by Redis will be recorded in the AOF file, which can be regarded as a command log file.
AOF is turned off by default. You need to modify the redis.conf configuration file to enable AOF:
The frequency of AOF command recording can also be passed through redis.conf File to match:
Configuration items | Flush timing | Advantages | Disadvantages |
---|---|---|---|
Always | Synchronous disk flush | High reliability, almost no data loss | Great impact on performance |
everysec | Flash disk per second | Moderate performance | Lost data for up to one minute |
no | Operating system control | Best performance | Poor reliability, may lose a lot of data |
Because it is a recording command, the AOF file will be much larger than the RDB file. Although AOF will record multiple write operations to the same key, only the last write operation among them is meaningful. You can use the bgrewriteaof command to complete the AOF file rewriting function with the minimum number of commands.
set id 1 set name nezha set id 2 bgrewriteaof mset name nezha id 2
Redis will also automatically rewrite the AOF file when the threshold is triggered. The threshold can also be configured in redis.conf:
# If the AOF file grows by more than the last file, the rewrite will be triggered. auto-aof-rewrite-percentage 100# What is the minimum size of the AOF file? Trigger rewrite auto-aof-rewrite-min-size 64mb
RDB and AOF each have their own advantages and disadvantages. If the data security requirements are high, the two are often combined in actual development to use.
AOF | ||
---|---|---|
Regular snapshots of the entire memory | Record every executed command | |
Incomplete, between two backups Will lose | Relatively complete, depends on the brushing strategy | |
There will be compression, the file size is small | records command, the file size is very large | |
Quickly | Slow | |
Low, because data integrity is not low | High, because data integrity is higher | |
High, a lot of CPU and memory consumption | Low, mainly disk IO resources, but AOF rewriting will occupy a lot of CPU and memory resources | |
Can tolerate data loss for several minutes and pursue faster startup speed | Common with higher requirements for data security |
- Query coupons;
- Judge flash sale product inventory;
- Query order
- Verify one order per person;
- Reduce inventory;
- Create an order;
- Add flash sale coupons and save the coupon information to Redis;
- Based on Lua script, determine the flash sale product inventory, one person per order, determine whether the user's flash sale is successful;
- If the flash sale is successful, encapsulate the coupon id, user id, and product id into the blocking queue;
- Start the asynchronous task and continuously remove the items from the blocking queue Read information and implement asynchronous ordering function;
public Result seckillVoucher(Long voucherId) {
Long userId = UserHolder.getUser().getId();
long orderId = redisIdWorker.nextId("order");
// 1.执行lua脚本
Long result = stringRedisTemplate.execute(
SECKILL_SCRIPT,
Collections.emptyList(),
voucherId.toString(), userId.toString(), String.valueOf(orderId)
);
int r = result.intValue();
// 2.判断结果是否为0
if (r != 0) {
// 2.1.不为0 ,代表没有购买资格
return Result.fail(r == 1 ? "库存不足" : "不能重复下单");
}
// 3.返回订单id
return Result.ok(orderId);
}
5. Through the thread pool, operate the blocking queue// 线程池
private static final ExecutorService SECKILL_ORDER_EXECUTOR = Executors.newSingleThreadExecutor();
/**
* 在类初始化完成后执行
*/
@PostConstruct
private void init() {
SECKILL_ORDER_EXECUTOR.submit(new VoucherOrderHandler());
}
// 阻塞队列
private BlockingQueue<VoucherOrder> orderTasks = new ArrayBlockingQueue<>(1024 * 1024);
private class OrderHandler implements Runnable{
@Override
public void run() {
while (true){
try {
doSomething();
} catch (Exception e) {
log.error("处理订单异常", e);
}
}
}
}
5. Implement shared session login based on RedisLogin based on session
public class RefreshTokenInterceptor implements HandlerInterceptor { private StringRedisTemplate stringRedisTemplate; public RefreshTokenInterceptor(StringRedisTemplate stringRedisTemplate) { this.stringRedisTemplate = stringRedisTemplate; } @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { // 1、获取请求头中的token String token = request.getHeader("authorization"); if (StrUtil.isBlank(token)) { return true; } // 2、基于TOKEN获取redis中的用户 String key = LOGIN_USER_KEY + token; Map<Object, Object> userMap = stringRedisTemplate.opsForHash().entries(key); // 3、判断用户是否存在 if (userMap.isEmpty()) { return true; } // 5、将查询到的hash数据转为UserDTO UserDTO userDTO = BeanUtil.fillBeanWithMap(userMap, new UserDTO(), false); // 6、存在,保存用户信息到 ThreadLocal UserHolder.saveUser(userDTO); // 7、刷新token有效期 stringRedisTemplate.expire(key, LOGIN_USER_TTL, TimeUnit.MINUTES); // 8、放行 return true; } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { // 移除用户 UserHolder.removeUser(); } }
The above is the detailed content of How to implement Redis distributed cache and flash sales. For more information, please follow other related articles on the PHP Chinese website!

Redis stands out because of its high speed, versatility and rich data structure. 1) Redis supports data structures such as strings, lists, collections, hashs and ordered collections. 2) It stores data through memory and supports RDB and AOF persistence. 3) Starting from Redis 6.0, multi-threaded I/O operations have been introduced, which has improved performance in high concurrency scenarios.

RedisisclassifiedasaNoSQLdatabasebecauseitusesakey-valuedatamodelinsteadofthetraditionalrelationaldatabasemodel.Itoffersspeedandflexibility,makingitidealforreal-timeapplicationsandcaching,butitmaynotbesuitableforscenariosrequiringstrictdataintegrityo

Redis improves application performance and scalability by caching data, implementing distributed locking and data persistence. 1) Cache data: Use Redis to cache frequently accessed data to improve data access speed. 2) Distributed lock: Use Redis to implement distributed locks to ensure the security of operation in a distributed environment. 3) Data persistence: Ensure data security through RDB and AOF mechanisms to prevent data loss.

Redis's data model and structure include five main types: 1. String: used to store text or binary data, and supports atomic operations. 2. List: Ordered elements collection, suitable for queues and stacks. 3. Set: Unordered unique elements set, supporting set operation. 4. Ordered Set (SortedSet): A unique set of elements with scores, suitable for rankings. 5. Hash table (Hash): a collection of key-value pairs, suitable for storing objects.

Redis's database methods include in-memory databases and key-value storage. 1) Redis stores data in memory, and reads and writes fast. 2) It uses key-value pairs to store data, supports complex data structures such as lists, collections, hash tables and ordered collections, suitable for caches and NoSQL databases.

Redis is a powerful database solution because it provides fast performance, rich data structures, high availability and scalability, persistence capabilities, and a wide range of ecosystem support. 1) Extremely fast performance: Redis's data is stored in memory and has extremely fast read and write speeds, suitable for high concurrency and low latency applications. 2) Rich data structure: supports multiple data types, such as lists, collections, etc., which are suitable for a variety of scenarios. 3) High availability and scalability: supports master-slave replication and cluster mode to achieve high availability and horizontal scalability. 4) Persistence and data security: Data persistence is achieved through RDB and AOF to ensure data integrity and reliability. 5) Wide ecosystem and community support: with a huge ecosystem and active community,

Key features of Redis include speed, flexibility and rich data structure support. 1) Speed: Redis is an in-memory database, and read and write operations are almost instantaneous, suitable for cache and session management. 2) Flexibility: Supports multiple data structures, such as strings, lists, collections, etc., which are suitable for complex data processing. 3) Data structure support: provides strings, lists, collections, hash tables, etc., which are suitable for different business needs.

The core function of Redis is a high-performance in-memory data storage and processing system. 1) High-speed data access: Redis stores data in memory and provides microsecond-level read and write speed. 2) Rich data structure: supports strings, lists, collections, etc., and adapts to a variety of application scenarios. 3) Persistence: Persist data to disk through RDB and AOF. 4) Publish subscription: Can be used in message queues or real-time communication systems.


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

WebStorm Mac version
Useful JavaScript development tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

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

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

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