阿里架构师分享:Redis短链接生成
来源:引流技巧
编辑:爱短链
时间:2025-08-12

短链接生成,浏览器获取原长地址的响应响应
实施
短地址服务的核心是短地址和长地址的转换映射算法。
最简单的算法是将原始长地址记录为MD5摘要作为key,长地址作为value。将key值放入redis等服务器缓存中。
逆向解析时通过URL解决key,比如上面的短地址key = 15uOVS。然后使用key从缓存中获取原始长地址值短链接生成,实现URL地址恢复。
MD5 摘要有几个明显的问题:
1、短地址的长度是有限的。例如行业见闻:阿里架构师分享:Redis短链接生成实战,网友:这个操作还可以吗?,MD5 后的数据长度为 32 位。为了使短地址足够短短链接生成,需要进行分段和循环处理
2、MD5的hash冲突问题有一定的重复概率。要解决这个问题,需要不断提高算法的复杂度,而且有些得不偿失
当然不止MD5的实现算法,你可以自己google一下。
代码实现
1:短连接工具类
import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Base64; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * 短网址的实现,不管多长,都生成四位链接 * * @author CHX */ public class ShortURL { private static String[] chars = new String[]{"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", "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"}; /** * 首先从URL中获取固定格式后的内容 * * @param longUrl 原url * @param yuMing 域名 */ public static String myTestShort(String longUrl, String yuMing) { String newurl = ""; String regex = "(http://|https://)" + yuMing + "(.*)"; Pattern r = Pattern.compile(regex); // 现在创建 matcher 对象 Matcher m = r.matcher(longUrl); if (m.find()) { String url = m.group(2); if (url != null) { // 此处就是生成的四位短连接 newurl = changes(url); //System.out.println(m.group(1) + yuMing + "/" + changes(url)); } } return newurl; } /** * 编码思路:考虑到base64编码后,url中只有[0-9][a-z][A-Z]这几种字符,所有字符共有26+26+10=62种 对应的映射表为62进制即可 * * @param value * @return */ public static String changes(String value) { // 获取base64编码 String stringBase64 = stringBase64(value); // 去除最后的==(这是base64的特征,最后以==结尾) stringBase64 = stringBase64.substring(0, stringBase64.length() - 2); MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } // 利用md5生成32位固长字符串 String mid = new String(bytesToHexString(md5.digest(stringBase64.getBytes()))); StringBuilder outChars = new StringBuilder(); for (int i = 0; i < 4; i++) { //每八个一组 String sTempSubString = mid.substring(i * 8, i * 8 + 8); // 想办法将此16进制的八个字符数缩减到62以内,所以取余,然后置换为对应的字母数字 outChars.append(chars[(int) (Long.parseLong(sTempSubString, 16) % chars.length)]); } return outChars.toString(); } /** * 将字符串转换为base64编码 * * @param text 原文 * @return */ public static String stringBase64(String text) { return Base64.getEncoder().encodeToString(text.getBytes()); } /** * 将byte转换为16进制的字符串 * * @param src * @return */ public static String bytesToHexString(byte[] src) { StringBuilder stringBuilder = new StringBuilder(); if (src == null || src.length <= 0) { return null; } for (int i = 0; i < src.length; i++) { int v = src[i] & 0xFF; String hv = Integer.toHexString(v); if (hv.length() < 2) { stringBuilder.append(0); } stringBuilder.append(hv); } return stringBuilder.toString(); } }2:redis配置
java依赖
org.springframework.bootspring-boot-starter-data-redis配置文件
##端口号 # Redis数据库索引(默认为0) spring.redis.database=0 # Redis服务器地址 spring.redis.host=192.168.124.20 # Redis服务器连接端口 spring.redis.port=6379 # Redis服务器连接密码(默认为空) spring.redis.password= #连接池最大连接数(使用负值表示没有限制) spring.redis.jedis.pool.max-idle=8 # 连接池最大阻塞等待时间(使用负值表示没有限制) spring.redis.jedis.pool.max-wait= # 连接池中的最大空闲连接 # 连接池中的最小空闲连接 spring.redis.jedis.pool.min-idle=0 # 连接超时时间(毫秒) spring.redis.timeout=300 import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.cache.annotation.CachingConfigurerSupport; import org.springframework.cache.annotation.EnableCaching; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.*; import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; import org.springframework.data.redis.serializer.StringRedisSerializer;
3:短连接使用
import com.eltyl.api.util.RedisUtil; import com.eltyl.api.util.ShortURL; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/redis/") public class EndLinkContronller { @Autowired private RedisUtil redisUtil; @RequestMapping("save") public String save(){ String plainUrl = "http://www.*.com/index.php?s=/Index/index/id/1.html"; String endlink = ShortURL.myTestShort(plainUrl,"www.*.com"); System.out.println(endlink); redisUtil.set(endlink,plainUrl); return "success"; }最后再建一个项目拦截一下,看看有没有来自redis的相对链接


相关文章:
相关推荐:
栏目分类

最新文章

热门文章
