1. //通过时间获取分布式id能力
    2. public class GenerateTimeBasedIdCapability extends SpringManagedCapability {
    3. private final static Logger logger = LoggerFactory.getLogger(GenerateTimeBasedIdCapability.class);
    4. @Resource
    5. private RedisClient redisClient;
    6. private final ThreadLocal<DateFormat> ssDateFormatThreadLocal = new ThreadLocal<DateFormat>() {
    7. @Override
    8. public DateFormat get() {
    9. DateFormat v = super.get();
    10. if (v == null) {
    11. v = new SimpleDateFormat("yyyyMMddHHmmss");
    12. super.set(v);
    13. }
    14. return v;
    15. }
    16. };
    17. public String execute(String idNamespace) {
    18. TimeWatch timeWatch = TimeWatch.start();
    19. String currDateStr = ssDateFormatThreadLocal.get().format(new Date());
    20. String idCountKey = CacheKeyManager.createIdCountKey(idNamespace, currDateStr);
    21. Long idCount = redisClient.incr(idCountKey);
    22. redisClient.expire(idCountKey, Constants.COUNT_EXPIRE_TIME);
    23. if (idCount == null) {
    24. KeyLogger.log(KeyLogConstants.Domain.IdGenerate.ID_GENERATE_CAPABILITY, Boolean.FALSE, "idNamespace",
    25. idNamespace);
    26. logger.error("incr error idNamespace:{}", idNamespace);
    27. ExceptionThrower.throwException(SysResultCodeEnum.IO_EXCEPTION);
    28. }
    29. Expectation.requireTrue(idCount < Constants.COUNT_MAX_NUM, ResultCodeEnum.COUNT_NUM_OUT_OF_RANGE);
    30. String idCountStr = StringUtils.leftPad(String.valueOf(idCount), Constants.COUNT_LEFT_PAD_LENGTH,
    31. Constants.COUNT_LEFT_PAD_CHAR);
    32. KeyLogger.log(KeyLogConstants.Domain.IdGenerate.ID_GENERATE_CAPABILITY, Boolean.TRUE, "idNamespace",
    33. idNamespace);
    34. KeyLogger.log(KeyLogConstants.Domain.IdGenerate.ID_GENERATE_CAPABILITY, timeWatch.endMS(), "idNamespace",
    35. idNamespace);
    36. return currDateStr + idCountStr;
    37. }
    38. }