Redis生成主键ID
使用Redis來生成主鍵ID策略,這裡主要使用
RedisAtomicLong
類來實現主鍵生成策略。具體代碼如下:
/**
* @Description: 获取自增长值
* @param key key
* @return
*/
public static Long getIncr(String key) {
RedisAtomicLong redisAtomicLong = new RedisAtomicLong(key,redisTemplate.getConnectionFactory());
Long increment = redisAtomicLong.getAndIncrement();
redisAtomicLong.expire(0, TimeUnit.SECONDS);
return increment;
}
/**
* @Description: 初始化自增长值
* @param key key
* @param value 当前值
*/
public void setIncr(String key, int value) {
RedisAtomicLong redisAtomicLong = new RedisAtomicLong(key, redisTemplate.getConnectionFactory());
redisAtomicLong.set(value);
redisAtomicLong.expire(0, TimeUnit.SECONDS);
}