【分布式-Redis应用】Spring中Redis使用项目实战(持续更新...)

场景及代码示例

1、list集合存储到Redis以及读取

  import org.springframework.data.redis.core.StringRedisTemplate;

  @Autowired
  private StringRedisTemplate redisTemplate;
  
  // 存入缓存,过期时间1h
  String cacheValue = JSONObject.parseArray(JSON.toJSONString(lsit)).toJSONString();
  redisTemplate.opsForValue().set(key, cacheValue, 1, TimeUnit.HOURS);

 /* 缓存中读取 */
 String childTemplatesStr = redisTemplate.opsForValue().get(key);
 List<TemplateInfo> cacheChildTemplates = JSONObject.parseArray(childTemplatesStr, TemplateInfo.class);

分布式锁及代码示例

1、Redisson实现分布式锁

关键点声明

各加锁方法对比
● 申明方法有无InterruptedException:方法申明时抛出 InterruptedException,表示当前方法在等待时,支持其他线程通过调用interrupt方法,中断当前线程方法的执行。
● 有无leaseTime:设置leaseTime即设置锁的过期时间,若无或leaseTime=-1L,则通过watchDog自动续锁。
● 有无waitTime:设置锁阻塞时的最大阻塞时间。
● lock和tryLock:往往lock是获取不到锁时阻塞,tryLock获取不到锁时也会立即返回,但如果包含waitTime参数,则另算。

有个Redisson分布式锁实现原理可参考文章:https://segmentfault.com/a/1190000040813126

Redisson分布式锁代码模板

1、
设置等待的时间,加锁的时间:
● 因为设置了等待的时间waitTime,那么当没有获取到锁的时候,会最大等待500s。
● 因为设置了加锁的时间leaseTime,那么当1500s之后,如果业务还没有执行完毕,则会是否锁。

RLock lock = redissonClient.getLock("LOCK_KEY");
long waitTime=500L;
long leaseTime=15000L;
boolean isLock = lock.tryLock(waitTime, leaseTime, TimeUnit.MILLISECONDS);
if (!isLock){
    
    
    log.info("lock conflict");
    return;
}

try {
    
    
     // do something ...
} catch (InterruptedException e) {
    
    
    Thread.currentThread().interrupt();
} finally {
    
    
    // 判断拿到锁的,是否是当前线程
    if (lock.isHeldByCurrentThread()) {
    
    
        lock.unlock();
   }
}

2、
没有设置等待时间,加锁的时间:
● 因为没有设置等待时间,当获取不到锁的时候,不会阻塞等待,而是直接返回。
● 因为没有设置加锁的时候,默认redisson会给30s的加锁时间。

RLock lock = redissonClient.getLock("LOCK_KEY");
boolean isLock = lock.tryLock();
if (!isLock){
    
    
    log.info("lock conflict");
    return;
}

try {
    
    
 // do something ...
} catch (InterruptedException e) {
    
    
    Thread.currentThread().interrupt();
} finally {
    
    
    // 判断拿到锁的,是否是当前线程
      if (lock.isHeldByCurrentThread()) {
    
    
        lock.unlock();
   }
}

2、Redis实现分布式锁

setNx

猜你喜欢

转载自blog.csdn.net/qq_43783527/article/details/129900145