Generating 8-character only UUIDs

后端 未结 8 1503
[愿得一人]
[愿得一人] 2020-11-27 03:22

UUID libraries generate 32-character UUIDs.

I want to generate 8-character only UUIDs, is it possible?

8条回答
  •  鱼传尺愫
    2020-11-27 04:00

    This is a similar way I'm using here to generate an unique error code, based on Anton Purin answer, but relying on the more appropriate org.apache.commons.text.RandomStringGenerator instead of the (once, not anymore) deprecated org.apache.commons.lang3.RandomStringUtils:

    @Singleton
    @Component
    public class ErrorCodeGenerator implements Supplier {
    
        private RandomStringGenerator errorCodeGenerator;
    
        public ErrorCodeGenerator() {
            errorCodeGenerator = new RandomStringGenerator.Builder()
                    .withinRange('0', 'z')
                    .filteredBy(t -> t >= '0' && t <= '9', t -> t >= 'A' && t <= 'Z', t -> t >= 'a' && t <= 'z')
                    .build();
        }
    
        @Override
        public String get() {
            return errorCodeGenerator.generate(8);
        }
    
    }
    

    All advices about collision still apply, please be aware of them.

提交回复
热议问题