接收长链接
用户输入一个长 URL,例如:https://www.example.com/products/special-offer?utm_source=google&utm_campaign=winter_sale

生成唯一标识(短码)

通过 哈希算法、Base62 编码,生成一个唯一的短链接后缀,如:3qYJOI

public class HashUtil {

    private static final char[] CHARS = new char[]{
            '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'
    };
    private static final int SIZE = CHARS.length;
    private static String convertDecToBase62(long num) {
        StringBuilder sb = new StringBuilder();
        while (num > 0) {
            int i = (int) (num % SIZE);
            sb.append(CHARS[i]);
            num /= SIZE;
        }
        return sb.reverse().toString();
    }
    public static String hashToBase62(String str) {
        int i = MurmurHash.hash32(str);
        long num = i < 0 ? Integer.MAX_VALUE - (long) i : i;
        return convertDecToBase62(num);
    }
}

存储映射关系

数据库(如 MySQL、Redis) 中存储 长 URL 和短码的映射关系

短链接访问

用户访问 https://short.com/3qYJOI

后端查询数据库,找到对应的 长 URL

进行 301 重定向:java复制编辑response.sendRedirect(“https://www.example.com/products/special-offer…”);

Categories:

Tags:

暂时没有回复

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注