短链接在线生成(阿里架构师分享:redis 短链接生成实战,网友:还能有这操作?)

背景

现在在各种圈的产品各种推广地址,由于URL地址过长,不美观、不方便收藏、发布、传播以及各种发文字数限制等问题,微信、微博都在使用短链接技术。最近由于使用的三方的生成、解析短链接服务开始限制使用以及准备收费、不方便统计分析、不方便流控等问题,决定自建一个短地址服务。

原理

比如,http://dx.*.com/15uOVS 这个短地址

第1步,浏览器请求这个地址

第2步,通过DNS后到短地址服务端,还原这个短地址对应的原始长地址。

第3步,请求http 301 或302到原始的长地址上

第4步,浏览器拿到原始长地址的响应response

实现

短地址服务的核心是短地址和长地址的转化映射算法。

最简单的算法是把原来的长地址做MD5摘要记为key,长地址记为value。把key value放入服务端缓存中比如redis中。

反向解析时通过URL解决出key来,比如上面的短地址key = 15uOVS 。然后通过key去缓存中获取原始长地址value实现URL地址还原。

MD5摘要有几个明显的问题:

1、短地址的长度受限,比如MD5后的数据长度是32位,需要进行分段循环处理,使短地址足够短

2、MD5的哈希碰撞问题,有一定的概率重复,解决此问题,需要不断的提升算法的复杂度,有些得不偿失

当然不止MD5实现算法比较多,大家可以自行谷歌。

代码实现

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依赖

<!--springboot中的redis依赖--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>

配置文件

##端口号 # 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; /** * redis配置类 * @program: springbootdemo * @Date: 2019/2/22 15:20 * @Author: zjjlive * @Description: */ @Configuration @EnableCaching //开启注解 public class RedisConfig extends CachingConfigurerSupport { /** * retemplate相关配置 * @param factory * @return */ @Bean public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) { RedisTemplate<String, Object> template = new RedisTemplate<>(); // 配置连接工厂 template.setConnectionFactory(factory); //使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值(默认使用JDK的序列化方式) Jackson2JsonRedisSerializer jacksonSeial = new Jackson2JsonRedisSerializer(Object.class); ObjectMapper om = new ObjectMapper(); // 指定要序列化的域,field,get和set,以及修饰符范围,ANY是都有包括private和public om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); // 指定序列化输入的类型,类必须是非final修饰的,final修饰的类,比如String,Integer等会跑出异常 om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jacksonSeial.setObjectMapper(om); // 值采用json序列化 template.setValueSerializer(jacksonSeial); //使用StringRedisSerializer来序列化和反序列化redis的key值 template.setKeySerializer(new StringRedisSerializer()); // 设置hash key 和value序列化模式 template.setHashKeySerializer(new StringRedisSerializer()); template.setHashValueSerializer(jacksonSeial); template.afterPropertiesSet(); return template; } /** * 对hash类型的数据操作 * * @param redisTemplate * @return */ @Bean public HashOperations<String, String, Object> hashOperations(RedisTemplate<String, Object> redisTemplate) { return redisTemplate.opsForHash(); } /** * 对redis字符串类型数据操作 * * @param redisTemplate * @return */ @Bean public ValueOperations<String, Object> valueOperations(RedisTemplate<String, Object> redisTemplate) { return redisTemplate.opsForValue(); } /** * 对链表类型的数据操作 * * @param redisTemplate * @return */ @Bean public ListOperations<String, Object> listOperations(RedisTemplate<String, Object> redisTemplate) { return redisTemplate.opsForList(); } /** * 对无序集合类型的数据操作 * * @param redisTemplate * @return */ @Bean public SetOperations<String, Object> setOperations(RedisTemplate<String, Object> redisTemplate) { return redisTemplate.opsForSet(); } /** * 对有序集合类型的数据操作 * * @param redisTemplate * @return */ @Bean public ZSetOperations<String, Object> zSetOperations(RedisTemplate<String, Object> redisTemplate) { return redisTemplate.opsForZSet(); } }

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里面看一下有没有存相对就的链接

import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @RestController public class IndexContronller { @Autowired private RedisUtil redisUtil; @RequestMapping("/**") public void save(HttpServletRequest request, HttpServletResponse response) throws IOException { System.out.println("用户想执行的操作是:"+request.getServletPath()); String newurl = request.getServletPath().replace("/",""); if(redisUtil.get(newurl)!=null){ System.out.println("存在"); //return "redirect:http://www.*.com"; response.sendRedirect("http://www.*.com"); }else{ System.out.println("不存在"); //return "redirect:http://new.*.com"; response.sendRedirect("http://news.*.com"); } //return "success"; } }

您可以还会对下面的文章感兴趣

最新评论

  1. 凉凉晨风
    凉凉晨风
    发布于:2022-04-27 13:16:03 回复TA
    ); System.out.println(endlink); redisUtil.set(endlink,plainUrl);
  1. 千面书生
    千面书生
    发布于:2022-04-27 16:07:35 回复TA
    ramework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.RequestMapping;import
  1. 单于巧珠欣
    单于巧珠欣
    发布于:2022-04-27 09:39:11 回复TA
    哥生活在杯具中说明老天让涐坚强不息。
  1. 邱东振瑶
    邱东振瑶
    发布于:2022-04-27 09:39:11 回复TA
    每个成功男人的背后,都有个折磨他的女人。

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

使用微信扫描二维码后

点击右上角发送给好友