Commit 2998ae2b by 林冲

修改车源号生成

1 parent 49eb783d
package com.gsc4cloud.gsc.vpc.api.util; package com.gsc4cloud.gsc.vpc.api.util;
import java.security.SecureRandom; import org.springframework.stereotype.Component;
/** /**
* @BelongsProject: glsx-accounts-test * @BelongsProject: glsx-accounts-test
...@@ -10,27 +10,51 @@ import java.security.SecureRandom; ...@@ -10,27 +10,51 @@ import java.security.SecureRandom;
* @Description: TODO * @Description: TODO
* @Version: 1.0 * @Version: 1.0
*/ */
@Component
public class ShortLinkComponent { public class ShortLinkComponent {
private static final SecureRandom RANDOM = new SecureRandom();
/** /**
* 62个字符 * 62个字符
*/ */
private static final String CHARS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; private static final String CHARS = "123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
private static final int DEFAULT_CODE_LENGTH = 6;
/** /**
* 随机生成指定长度的字符串 * 生成短链码
* @param length 长度 * @param param
* @return 随机字符串 * @return
*/ */
public static String randomCode(int length) { public String createShortLinkCode(String param){
StringBuilder sb = new StringBuilder(length); long murmurhash = CommonUtil.murmurHash32(param);
for (int i = 0; i < length; i++) { //进制转换
int index = RANDOM.nextInt(CHARS.length()); String code = encodeToBase61(murmurhash);
sb.append(CHARS.charAt(index)); if (code.length() < DEFAULT_CODE_LENGTH) {
StringBuilder builder = new StringBuilder(code);
while (builder.length() < DEFAULT_CODE_LENGTH) {
builder.append('0');
}
code = builder.toString();
} }
return sb.toString(); return code;
}
/**
* 10进制转61进制
* @param num
* @return
*/
private String encodeToBase61(long num){
// StringBuffer线程安全,StringBuilder线程不安全
StringBuffer sb = new StringBuffer();
do{
int i = (int )(num%61);
sb.append(CHARS.charAt(i));
num = num/61;
}while (num>0);
String value = sb.reverse().toString();
return value;
} }
} }
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!