Redis实现全局唯一id生成
废话不多说直接上代码
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.concurrent.TimeUnit;
/**
* 描述:
* 唯一ID生成器
* @author jimmy
* @create 2020-11-06 16:06
*/
@Component
public class GenerateIDUtil {
@Autowired
private RedisTemplate redisTemplate;
/**
* 生成每天的初始Id
* @param key
* @return
*/ public String initPrimaryId(String key) {
Assert.hasLength(key, "hashName不能为空");
String hashCol = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
//自定义编号规则
String hashColVal = hashCol + "00001";
// redisTemplate.opsForHash().putIfAbsent(hashName, hashCol, hashColVal);
Long expiresTime = getSecondsNextEarlyMorning();
redisTemplate.opsForValue().set(key, Long.valueOf(hashColVal), expiresTime, TimeUnit.SECONDS);
return hashColVal;
}
/**
* 获取分布式Id
* @param key
* @return
*/
public String getPrimaryId(String key) {
String id = "";
if(redisTemplate.hasKey(key)){
// redisTemplate.opsForValue().get(key);
// redisTemplate.delete(key);
id = String.valueOf(redisTemplate.opsForValue().increment(key, 1));
} else {
id = initPrimaryId(key);
}
return id;
}
/**
* 判断当前时间距离第二天凌晨的秒数
* @return 返回值单位为[s:秒]
*/
public Long getSecondsNextEarlyMorning() {
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;
}
}
写法很简单,没什么可说的。