search
HomeDatabaseRedisHow to solve the problem of redis expiration time

1. If you modify a redis' String expiration key multiple times, how to ensure that it can still retain the deletion time when it was first set

For modifying String, redis has: set, setex, append , incr, decr, etc. Among them, using set and setex to modify the original existing String will reset the originally set expiration time. Strictly speaking, set and setex are not "modifications" but overwriting, so the original settings If the key-value has been passed, set/setex this key again will overwrite the original one. The test results using try redis are as follows:

How to solve the problem of redis expiration time

If you use append, incr, decr and other commands to modify, the original expiration time will not be reset:

How to solve the problem of redis expiration time

So, for the string structure, as long as the set /setex command is executed, the expiration time will be reset, and the set command will directly change the expiration time to never expire.
For example, if I set a {key1:value} at 7:00, the expiration time is 30 minutes, and if I set/setex the value of this key multiple times between 7:00-7:30, the expiration time of key1 will be reset. settings and will eventually not expire at 7:30. How to ensure that the expiration time is not refreshed every time after setting this expiration key, and the expiration is stable at 7:30?

Method 1:

Use Timer, create a timer when setting for the first time, and delete the key when it expires. This method will occupy more CPU resources when the amount of data is large, and is not recommended.

Method 2:

Before setting the value of the key each time, return the remaining expiration time of the key at this time, and assign the remaining expiration time to the key as the new expiration time during setex Time will solve it.

Taking the Spring project as an example, it can be solved by using the remaining expiration timestamp (millisecond level) returned by the redisTemplate.getExpire(String key) method. Essentially, it sends a PTTL command to redis to return milliseconds. The remaining expiration time of the unit's key.

How to solve the problem of redis expiration time

Code example:

Let key1 keep the expiration time when it is first set every time it is modified

//获取key1的剩余时间的时间戳
Long expire = redisTemplate.getExpire("key1");
//最后一个参数可以选秒、毫秒(TimeUnit.MILLISECONDS),Redis最多只能返回毫秒级别的key的剩余过期时间
redisTemplate.opsForValue().set(key, value, expire, TimeUnit.SECONDS);

2 .Will modifying the values ​​of hash, set, Zset, and list reset the expiration time?

The validity period of K-V of String type will be re-timed as the value value is modified:

If there is a K-V, the expiration time is 30 seconds. If the value value is modified, Then the expiration time will be reset to 30 seconds, instead of the original set time minus the lost time.

Except for the string data structure, modifications to other data structures will not reset the expiration time

For example, hash, set, Zset, list, etc.:

Take hash as an example:

The validity period of hash will not be re-timed as the hash field value is modified.
If you need to retime, you need to re-specify the validity period when modifying the field value.

How to solve the problem of redis expiration time

The above is the detailed content of How to solve the problem of redis expiration time. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
Redis's Server-Side Operations: What It OffersRedis's Server-Side Operations: What It OffersApr 29, 2025 am 12:21 AM

Redis'sServer-SideOperationsofferFunctionsandTriggersforexecutingcomplexoperationsontheserver.1)FunctionsallowcustomoperationsinLua,JavaScript,orRedis'sscriptinglanguage,enhancingscalabilityandmaintenance.2)Triggersenableautomaticfunctionexecutionone

Redis: Database or Server? Demystifying the RoleRedis: Database or Server? Demystifying the RoleApr 28, 2025 am 12:06 AM

Redisisbothadatabaseandaserver.1)Asadatabase,itusesin-memorystorageforfastaccess,idealforreal-timeapplicationsandcaching.2)Asaserver,itsupportspub/submessagingandLuascriptingforreal-timecommunicationandserver-sideoperations.

Redis: The Advantages of a NoSQL ApproachRedis: The Advantages of a NoSQL ApproachApr 27, 2025 am 12:09 AM

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: Understanding Its Architecture and PurposeRedis: Understanding Its Architecture and PurposeApr 26, 2025 am 12:11 AM

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.

Redis vs. SQL Databases: Key DifferencesRedis vs. SQL Databases: Key DifferencesApr 25, 2025 am 12:02 AM

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.

Redis: How It Acts as a Data Store and ServiceRedis: How It Acts as a Data Store and ServiceApr 24, 2025 am 12:08 AM

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

Redis vs. Other Databases: A Comparative AnalysisRedis vs. Other Databases: A Comparative AnalysisApr 23, 2025 am 12:16 AM

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's Role: Exploring the Data Storage and Management CapabilitiesRedis's Role: Exploring the Data Storage and Management CapabilitiesApr 22, 2025 am 12:10 AM

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.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools