//通过时间获取分布式id能力
public class GenerateTimeBasedIdCapability extends SpringManagedCapability {
private final static Logger logger = LoggerFactory.getLogger(GenerateTimeBasedIdCapability.class);
@Resource
private RedisClient redisClient;
private final ThreadLocal<DateFormat> ssDateFormatThreadLocal = new ThreadLocal<DateFormat>() {
@Override
public DateFormat get() {
DateFormat v = super.get();
if (v == null) {
v = new SimpleDateFormat("yyyyMMddHHmmss");
super.set(v);
}
return v;
}
};
public String execute(String idNamespace) {
TimeWatch timeWatch = TimeWatch.start();
String currDateStr = ssDateFormatThreadLocal.get().format(new Date());
String idCountKey = CacheKeyManager.createIdCountKey(idNamespace, currDateStr);
Long idCount = redisClient.incr(idCountKey);
redisClient.expire(idCountKey, Constants.COUNT_EXPIRE_TIME);
if (idCount == null) {
KeyLogger.log(KeyLogConstants.Domain.IdGenerate.ID_GENERATE_CAPABILITY, Boolean.FALSE, "idNamespace",
idNamespace);
logger.error("incr error idNamespace:{}", idNamespace);
ExceptionThrower.throwException(SysResultCodeEnum.IO_EXCEPTION);
}
Expectation.requireTrue(idCount < Constants.COUNT_MAX_NUM, ResultCodeEnum.COUNT_NUM_OUT_OF_RANGE);
String idCountStr = StringUtils.leftPad(String.valueOf(idCount), Constants.COUNT_LEFT_PAD_LENGTH,
Constants.COUNT_LEFT_PAD_CHAR);
KeyLogger.log(KeyLogConstants.Domain.IdGenerate.ID_GENERATE_CAPABILITY, Boolean.TRUE, "idNamespace",
idNamespace);
KeyLogger.log(KeyLogConstants.Domain.IdGenerate.ID_GENERATE_CAPABILITY, timeWatch.endMS(), "idNamespace",
idNamespace);
return currDateStr + idCountStr;
}
}