在软件开发中 id 通常为 int 或者 long 类型,有时会有混淆 id 的需求,比如反爬虫。Hashids 是一个小型的开源库,可以将数字或者十六进制字符串转换成唯一的、非顺序的 id。
使用
添加依赖
1 | <dependency> |
编码一个数字
1 | Hashids hashids = new Hashids("this is my salt"); |
解码一个数字
1 | Hashids hashids = new Hashids("this is my salt"); |
编码几个数字
1 | Hashids hashids = new Hashids("this is my salt"); |
指定编码结果的最小长度
1 | Hashids hashids = new Hashids("this is my salt", 8); |
指定编码结果使用的字母表
1 | Hashids hashids = new Hashids("this is my salt", 0, "0123456789abcdef"); |
编码十六进制字符串
1 | Hashids hashids = new Hashids("This is my salt"); |
解码十六进制字符串
1 | Hashids hashids = new Hashids("This is my salt"); |
注意事项
Java 版本是基于 JS 版本实现,因为 JS 对数字的范围限制是 2^53 - 1 (9007199254740991),为了保持兼容,Java 版本也保留了此限制,如果大于此数字将抛出 IllegalArgumentException 异常。
如果想要编码大于 9007199254740991 的数字可以使用编码十六进制字符串的方法。