search
HomeDatabaseRedisWhat is the solution for Java to operate redis and set expiration in the early morning of the next day?

Java operation redis setting expires in the early morning of the next day

Scenario

When querying data, I encountered the problem of needing to set the data to expire the next day in redis, but redis has There is no corresponding API, so we have to solve it by ourselves

Ideas

Calculate the time difference between the early morning of the next day and the current time, and set the time difference as the expiration time of redis, we can achieve The desired effect

code

/**
     * 计算第二天凌晨与当前时间的时间差秒数
     * @param
     * @return java.lang.Long
     * @author shy
     * @date 2021/3/12 18:10
     */
    public static Long getNowToNextDaySeconds() {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DAY_OF_YEAR, 1);
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.MILLISECOND, 0);
        return (cal.getTimeInMillis() - System.currentTimeMillis()) / 1000;
    }

gets the time difference, and the rest is basically no problem.

Attached is the Redis tool class:

/**
 * 操作redis
 * @author shy
 * @date 2020/12/10 10:01
 */
@Service
public class RedisService {
	
	@Autowired
	private StringRedisTemplate stringRedisTemplate;
	
	@Autowired
    private RedisTemplate<String, Object> redisTemplate;
	
	/**
	 * 判断String类型key是否存在
	 *
	 * @param key
	 * @return 
	 * @author shy
	 * @date 2018年11月13日 下午1:40:37
	 */
	public boolean hasStringKey(String key) {
		if (StringUtils.isBlank(key)) {
			throw new EmptyParameterException();
		}
		return stringRedisTemplate.opsForValue().getOperations().hasKey(key);
	}
	
	/**
	 * 判断String类型key是否存在
	 *
	 * @param key
	 * @return 
	 * @author shy
	 * @date 2018年11月13日 下午1:43:51
	 */
	public boolean nonStringKey(String key) {
		return !hasStringKey(key);
	}
	/**
	 * 设置String类型key,String类型value,过期时间timeout,TimeUnit
	 *
	 * @param key
	 * @param value
	 * @param timeout
	 * @param timeUnit
	 * @author shy
	 * @date 2018年12月10日13:53:38
	 */
	public void setStringKey(String key, String value, Long timeout, TimeUnit timeUnit) {
		if (StringUtils.isBlank(key) || Objects.isNull(timeout)) {
			throw new EmptyParameterException();
		}
		stringRedisTemplate.opsForValue().set(key, value, timeout, timeUnit);
	}
	
	public void setStringKey(String key, String value) {
		if (StringUtils.isBlank(key)) {
			throw new EmptyParameterException();
		}
		stringRedisTemplate.opsForValue().set(key, value);
	}
	/**
	 * 获取String类型value
	 *
	 * @param key
	 * @return
	 * @author shy
	 * @date 2018年11月12日 下午7:09:31
	 */
	public String getStringValue(String key) {
		if (StringUtils.isBlank(key)) {
			throw new EmptyParameterException();
		}
		return stringRedisTemplate.opsForValue().get(key);
	}
	
	/**
	 *	获取Key的过期时间
	 *
	 * @param key
	 * @return
	 * @author shy
	 * @date 2019年4月25日17:28:36
	 */
	public Long getExpire(String key) {
		if (StringUtils.isBlank(key)) {
			throw new EmptyParameterException();
		}
		return stringRedisTemplate.getExpire(key);
	}
	
	/**
	 *	设置Key的过期时间
	 *
	 * @param key
	 * @return
	 * @author shy
	 * @date 2019年4月25日17:28:36
	 */
	public Boolean setExpire(String key,Long timeout, TimeUnit timeUnit) {
		if (StringUtils.isBlank(key)) {
			throw new EmptyParameterException();
		}
		return stringRedisTemplate.expire(key, timeout, timeUnit);
	}	
	
	/**
	 * value自增+n
	 * @param key
	 * @return
	 * @author shy
	 * @date 2019年4月8日15:54:30
	 */
	public Long setIncrementValue(String key) {
		if (StringUtils.isBlank(key)) {
			throw new EmptyParameterException();
		}
		return stringRedisTemplate.opsForValue().increment(key, 1L);
	}
	/**
	 * 设置String类型key,Object类型value,过期时间timeout
	 *
	 * @param key
	 * @param value
	 * @param timeout
	 * @author shy
	 * @date 2018年12月10日13:54:07
	 */
	public void setObjectKey(String key, Object value, Long timeout,TimeUnit time) {
		if (StringUtils.isBlank(key) || Objects.isNull(timeout)) {
			throw new EmptyParameterException();
		}
		redisTemplate.opsForValue().set(key, value, timeout, time);
	}
	
	public void setObjectKey(String key, Object value) {
		if (StringUtils.isBlank(key)) {
			throw new EmptyParameterException();
		}
		redisTemplate.opsForValue().set(key, value);
	}
	
	/**
	 * 获取Object类型value
	 *
	 * @param key
	 * @param clazz
	 * @return 
	 * @author shy
	 * @date 2019年11月6日10:01:30
	 */
	@SuppressWarnings("unchecked")
	public <T> T getObjectValue(String key, Class<T> clazz) {
		if (StringUtils.isBlank(key)) {
			return null;
		}
		return (T) redisTemplate.opsForValue().get(key);
	}
	
	/**
	 * 移除单个String类型key
	 *
	 * @param key 
	 * @author shy
	 * @date 2018年11月13日 上午10:42:01
	 */
	public void removeSingleStringKey(String key) {
		if (StringUtils.isBlank(key)) {
			throw new EmptyParameterException();
		}
		stringRedisTemplate.opsForValue().getOperations().delete(key);
	}
	
	/**
	 * 移除Collection<String>类型keys
	 *
	 * @param keys 
	 * @author shy
	 * @date 2018年11月13日 下午3:15:16
	 */
	public void removeMultiStringKey(Collection<String> keys) {
		if (CollectionUtils.isNotEmpty(keys)) {
			stringRedisTemplate.opsForValue().getOperations().delete(keys);
		}
	}
	
	/**
	 * redis key 模糊查询
	 * @author shy
	 * @date 2021年1月4日 上午11:21:45
	 * @param key
	 * @return
	 */
	public Set<String> queryStringKeys(String key) {
		 return redisTemplate.keys(key + "*");
	}
}

redis expiration policy function introduction

When we use redis, we usually set an expiration time, of course There are also those that do not set an expiration time, that is, they will never expire.

When we set the expiration time, how does redis determine whether it has expired, and what strategy is used to delete it.

Set expiration time

When we set the key, we can give an expire time, which is the expiration time. For example, specify that this key can only survive for one hour. Suppose you set a batch of keys to survive for one hour. hour, then how does redis delete this batch of keys one hour later?

The answer is: regular deletion and lazy deletion.

The so-called regular deletion means that by default, redis randomly selects some keys with expiration time set every 100ms, checks whether they have expired, and deletes them if they expire. Traversing all keys with expiration times every 100ms will cause a significant performance drop, please note. Redis will actually randomly select some keys to check and delete every 100 milliseconds.

But the problem is that regular deletion may cause many expired keys to not be deleted when the time is up, so you need to delete them lazily. That is to say, when you get a key, redis will check to see if this key is set. Expiration time So has it expired? If it expires, it will be deleted.

By combining the above two methods, it is guaranteed that expired keys will be killed. All expired keys will not be automatically deleted when the expiration time is reached, so the memory usage will not be reduced after expiration.

But in fact this is still a problem. If a lot of expired keys are missed by regular deletion, and then they are not checked in time and lazy deletion is not carried out, it will cause a large number of expired keys to accumulate in the memory and consume redis memory. , how to deal with this situation?

The answer is: use the memory elimination mechanism.

Memory elimination

If redis takes up too much memory, some elimination will be carried out at this time. There are some strategies as follows:

  • noeviction: When the memory is not enough to accommodate the newly written data, the newly written data will report an error. This actual scenario is generally not used.

  • allkeys-lru: When the memory is not enough to accommodate the newly written data, in the key space, remove the least used key (this is the most commonly used )

  • allkeys-random: When the memory is not enough to accommodate the newly written data, a key is randomly removed from the key space. This is generally used. a bit less.

  • volatile-lru: When the memory is insufficient to accommodate newly written data, in the key space with an expiration time set, remove the least recently used key .

  • volatile-random: When the memory is insufficient to accommodate newly written data, a key is randomly removed from the key space with an expiration time set.

  • volatile-ttl: When the memory is not enough to accommodate the newly written data, in the key space with an expiration time set, there are keys with an earlier expiration time. Prioritize removal.

Memory elimination will trigger elimination conditions to delete certain keys. This is also the reason why keys are lost without setting an expiration time.

The above is the detailed content of What is the solution for Java to operate redis and set expiration in the early morning of the next day?. 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: Beyond SQL - The NoSQL PerspectiveRedis: Beyond SQL - The NoSQL PerspectiveMay 08, 2025 am 12:25 AM

Redis goes beyond SQL databases because of its high performance and flexibility. 1) Redis achieves extremely fast read and write speed through memory storage. 2) It supports a variety of data structures, such as lists and collections, suitable for complex data processing. 3) Single-threaded model simplifies development, but high concurrency may become a bottleneck.

Redis: A Comparison to Traditional Database ServersRedis: A Comparison to Traditional Database ServersMay 07, 2025 am 12:09 AM

Redis is superior to traditional databases in high concurrency and low latency scenarios, but is not suitable for complex queries and transaction processing. 1.Redis uses memory storage, fast read and write speed, suitable for high concurrency and low latency requirements. 2. Traditional databases are based on disk, support complex queries and transaction processing, and have strong data consistency and persistence. 3. Redis is suitable as a supplement or substitute for traditional databases, but it needs to be selected according to specific business needs.

Redis: Introduction to a Powerful In-Memory Data StoreRedis: Introduction to a Powerful In-Memory Data StoreMay 06, 2025 am 12:08 AM

Redisisahigh-performancein-memorydatastructurestorethatexcelsinspeedandversatility.1)Itsupportsvariousdatastructureslikestrings,lists,andsets.2)Redisisanin-memorydatabasewithpersistenceoptions,ensuringfastperformanceanddatasafety.3)Itoffersatomicoper

Is Redis Primarily a Database?Is Redis Primarily a Database?May 05, 2025 am 12:07 AM

Redis is primarily a database, but it is more than just a database. 1. As a database, Redis supports persistence and is suitable for high-performance needs. 2. As a cache, Redis improves application response speed. 3. As a message broker, Redis supports publish-subscribe mode, suitable for real-time communication.

Redis: Database, Server, or Something Else?Redis: Database, Server, or Something Else?May 04, 2025 am 12:08 AM

Redisisamultifacetedtoolthatservesasadatabase,server,andmore.Itfunctionsasanin-memorydatastructurestore,supportsvariousdatastructures,andcanbeusedasacache,messagebroker,sessionstorage,andfordistributedlocking.

Redis: Unveiling Its Purpose and Key ApplicationsRedis: Unveiling Its Purpose and Key ApplicationsMay 03, 2025 am 12:11 AM

Redisisanopen-source,in-memorydatastructurestoreusedasadatabase,cache,andmessagebroker,excellinginspeedandversatility.Itiswidelyusedforcaching,real-timeanalytics,sessionmanagement,andleaderboardsduetoitssupportforvariousdatastructuresandfastdataacces

Redis: A Guide to Key-Value Data StoresRedis: A Guide to Key-Value Data StoresMay 02, 2025 am 12:10 AM

Redis is an open source memory data structure storage used as a database, cache and message broker, suitable for scenarios where fast response and high concurrency are required. 1.Redis uses memory to store data and provides microsecond read and write speed. 2. It supports a variety of data structures, such as strings, lists, collections, etc. 3. Redis realizes data persistence through RDB and AOF mechanisms. 4. Use single-threaded model and multiplexing technology to handle requests efficiently. 5. Performance optimization strategies include LRU algorithm and cluster mode.

Redis: Caching, Session Management, and MoreRedis: Caching, Session Management, and MoreMay 01, 2025 am 12:03 AM

Redis's functions mainly include cache, session management and other functions: 1) The cache function stores data through memory to improve reading speed, and is suitable for high-frequency access scenarios such as e-commerce websites; 2) The session management function shares session data in a distributed system and automatically cleans it through an expiration time mechanism; 3) Other functions such as publish-subscribe mode, distributed locks and counters, suitable for real-time message push and multi-threaded systems and other scenarios.

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

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment