- 前言: 在app内分享链接到微信,会出现链接太长的情况,写了个工具类将长链接转成短链接
- 原理:
- 通过redis的原子递增作为计数器
- 将十进制转成62进制缩短链接
- redis存储长链接和短链接的映射关系
@RequiredArgsConstructor
@Component
public class LongLinkToShortUtil {
private final RedisTemplate<String,String> redisTemplate;
private static final String SHORT_URL_KEY = "SHORT_URL_KEY";
private static final String LOCALHOST = "http://localhost:8080/";
private static final String SHORT_LONG_PREFIX = "short_long_prefix_";
private static final String CACHE_KEY_PREFIX = "cache_key_prefix_";
final static char[] charSet = {'0', '1', '2', '3', '4', '5', '6', '7', '8',
'9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L',
'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'v', 'W', 'x', 'Y',
'z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u', 'V', 'w', 'X', 'y', 'Z'
};
public String getShortUrl(String longUrl) {
String cache = redisTemplate.opsForValue().get(CACHE_KEY_PREFIX + longUrl);
if (cache != null) {
return LOCALHOST + hex10To62(Long.valueOf(cache));
}
Long num = redisTemplate.opsForValue().increment(SHORT_URL_KEY);
String shortStr = hex10To62(num);
redisTemplate.opsForValue().set(SHORT_LONG_PREFIX + shortStr, longUrl);
redisTemplate.opsForValue().set(CACHE_KEY_PREFIX + longUrl, shortStr, 60 * 60, TimeUnit.SECONDS);
return LOCALHOST + shortStr;
}
public String hex10To62(Long number){
Long rest=number;
Stack<Character> stack=new Stack<>();
StringBuilder result=new StringBuilder(0);
while(rest!=0){
stack.add(charSet[new Long((rest-(rest/62)*62)).intValue()]);
rest=rest/62;
}
while (!stack.isEmpty()) {
result.append(stack.pop());
}
return result.toString();
}
}