code segmentredis
private static final String LOCK_SUCCESS = "OK"; private static final String SET_IF_NOT_EXIST = "NX"; private static final String SET_WITH_EXPIRE_TIME = "EX"; private static final String LOCKED = "locked"; /** * 加鎖 * * @param key redis key * @param seconds 過時時間 * @return 若是加鎖成功, 返回true, 反之, 返回false */ public boolean lock(String key, Integer seconds) { final String newKey = String.format(RedisConstant.PREFIX, key); String exist = ""; try { exist = redisTemplate.execute(action -> action.set(newKey, LOCKED, SET_IF_NOT_EXIST, SET_WITH_EXPIRE_TIME, seconds)); } catch (Exception e) { logger.error("lock error", e); } return exist != null && exist.equals(LOCK_SUCCESS); }
code segment緩存
redisTemplate.execute(redis -> redis.setex(redisKey, expiredTime,value));
code segment分佈式
String value = redisTemplate.execute(action -> action.get(key));
code segmentcode
Long remainSeconds = 0L; try { remainSeconds = redisTemplate.execute(action -> action.ttl(key)); } catch (Exception ex) { logger.error("redis ttl error", ex); } if (remainSeconds <= 0L) { //some logic }