1. /**
    2. * 生成id
    3. * @author ml
    4. * @param <ID> id
    5. */
    6. public interface IdGenerator<ID extends Serializable> {
    7. /**
    8. * 获取id
    9. * @return ID 返回19位id
    10. */
    11. ID generator();
    12. }
    1. /**
    2. * 生成19位分布式id
    3. *
    4. * @author ml
    5. * 当前id地址随机数 + 当前时间戳随机数+ 启动时间戳随机数 + 启动随机数 + 请求次数
    6. */
    7. @Component("idGenerator")
    8. public class LongIdGenerator implements IdGenerator<Long> {
    9. private static int counter = 0;
    10. private static final int IP_RANDOM_INT;
    11. private static final int JVM_RANDOM_INT;
    12. private static final int LAST_RANDOM_INT;
    13. static {
    14. long timeMillis = System.currentTimeMillis();
    15. int ip;
    16. try {
    17. ip = toInt(InetAddress.getLocalHost().getAddress());
    18. } catch (Exception e) {
    19. ip = 0;
    20. }
    21. Random ipRandom = new Random(ip);
    22. Random jvmRandom = new Random(timeMillis);
    23. Random lastRandom = new Random();
    24. IP_RANDOM_INT = ipRandom.nextInt(800) + 100;
    25. JVM_RANDOM_INT = jvmRandom.nextInt(90) + 10;
    26. LAST_RANDOM_INT = lastRandom.nextInt(10000);
    27. }
    28. @Override
    29. public Long generator() {
    30. //1970年1月1日0点 到现在的秒数
    31. long millisecond = System.currentTimeMillis();
    32. int count = LAST_RANDOM_INT + this.getCount();
    33. return (long) IP_RANDOM_INT * 10000000000000000L + millisecond * 100000L + (JVM_RANDOM_INT * 10000L) + (long) count;
    34. }
    35. protected int getCount() {
    36. synchronized (LongIdGenerator.class) {
    37. if (counter < 0) {
    38. counter = 0;
    39. }
    40. return counter++;
    41. }
    42. }
    43. private static int toInt(byte[] bytes) {
    44. int result = 0;
    45. for (int i = 0; i < 4; ++i) {
    46. result = (result << 8) - -128 + bytes[i];
    47. }
    48. return result;
    49. }
    50. }

    测试代码:

    1. @Autowired
    2. private IdGenerator<Long> generator;
    3. @RequestMapping("/findId")
    4. public Long findId(){
    5. return generator.generator();
    6. }

    image.png