Spring类 ValueOperations.setIfAbsent(K key, V value)方法

setIfAbsent

Spring 文档 https://docs.spring.io/spring-data/redis/docs/current/api/org/springframework/data/redis/core/ValueOperations.html#setIfAbsent(K,V)
@Nullable
Boolean setIfAbsent(K key, V value, long timeout, TimeUnit unit)
Set key to hold the string value and expiration timeout if key is absent.

Parameters:

  • key - must not be null.
  • value - must not be null.
  • timeout - the key expiration timeout.
  • unit - must not be null.

Returns:
null when used in pipeline / transaction.

See Also:
Redis Documentation: SET https://redis.io/docs/latest/commands/set/

Redis的SET

设置键以保存字符串值。如果键已保存值,则无论其类型如何,该值都会被覆盖。成功设置键后,与该键关联的任何先前的生存时间都将被丢弃。
Set key to hold the string value. If key already holds a value, it is overwritten, regardless of its type. Any previous time to live associated with the key is discarded on successful SET operation.

举例

Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);

通过 setIfAbsent 方法尝试获取锁,并在获取成功后设置过期时间,以防止死锁。

posted @ 2025-04-09 14:58  kuki'  阅读(89)  评论(0)    收藏  举报