代码工具---长链接转换短链接
生活随笔
收集整理的這篇文章主要介紹了
代码工具---长链接转换短链接
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
方式一
缺點(diǎn):數(shù)據(jù)加密性不好,容易被猜出來(lái),比如,產(chǎn)生數(shù)據(jù):00001、然后被惡意撞庫(kù)00002
優(yōu)點(diǎn):嚴(yán)格的自增id,不會(huì)產(chǎn)生重復(fù)的短key
maven 依賴
工具源碼:
import org.apache.commons.lang.StringUtils;/*** @author chunyang.leng* @date 2021-10-25 9:17 上午*/ public class ShortUrl {/*** 進(jìn)制*/private static final int SCALE = 62;/*** 最小長(zhǎng)度,超過(guò)該長(zhǎng)度,自動(dòng)補(bǔ)0*/private static final int MIN_LENGTH = 5;/*** 常量字符串*/private static final String chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";/*** 數(shù)字轉(zhuǎn)指定進(jìn)制編碼* @see ShortUrl#SCALE 進(jìn)制* @param num 待轉(zhuǎn)換待數(shù)據(jù)id,可以為雪花id,或者數(shù)據(jù)庫(kù)自增數(shù)據(jù)id* @return 62進(jìn)制編碼*/public static String encode(long num) {StringBuilder sb = new StringBuilder();int remainder;while (num > SCALE - 1) {// 對(duì) scale 進(jìn)行求余,然后將余數(shù)追加至 sb 中,由于是從末位開始追加的,因此最后需要反轉(zhuǎn)字符串remainder = Long.valueOf(num % SCALE).intValue();sb.append(chars.charAt(remainder));// 除以進(jìn)制數(shù),獲取下一個(gè)末尾數(shù)num = num / SCALE;}sb.append(chars.charAt(Long.valueOf(num).intValue()));String value = sb.reverse().toString();return StringUtils.leftPad(value, MIN_LENGTH, '0');}/*** 指定進(jìn)制轉(zhuǎn)為數(shù)字* @see ShortUrl#SCALE 進(jìn)制* @param str 加密字符串* @return 原始數(shù)據(jù)id*/public static long decode(String str) {//將 0 開頭的字符串進(jìn)行替換str = str.replace("^0*", "");long value = 0;char tempChar;int tempCharValue;for (int i = 0; i < str.length(); i++) {//獲取字符tempChar = str.charAt(i);//單字符值tempCharValue = chars.indexOf(tempChar);//單字符值在進(jìn)制規(guī)則下表示的值value += (long) (tempCharValue * Math.pow(SCALE, str.length() - i - 1));}return value;}}方式二
缺點(diǎn):依托外部存儲(chǔ),需要自行解決存儲(chǔ)和kv映射問(wèn)題,包括并發(fā)問(wèn)題等,生成的key可能存在碰撞情況
優(yōu)點(diǎn):加密型好,撞庫(kù)可能性不大
總結(jié)
以上是生活随笔為你收集整理的代码工具---长链接转换短链接的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: python解决数学问题_用python
- 下一篇: html实现播放暂停,html如何实现播