设为首页 - 加入收藏
广告 1000x90
您的当前位置:主页 > 网络营销 > 正文

阿里架构师分享: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; /*** 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 RedisTemplateredisTemplate(RedisConnectionFactory factory) {        RedisTemplatetemplate = 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 HashOperationshashOperations(RedisTemplateredisTemplate) {        return redisTemplate.opsForHash();    }    /**     * 对redis字符串类型数据操作     *     * @param redisTemplate     * @return     */    @Bean    public ValueOperationsvalueOperations(RedisTemplateredisTemplate) {        return redisTemplate.opsForValue();    }    /**     * 对链表类型的数据操作     *     * @param redisTemplate     * @return     */    @Bean    public ListOperationslistOperations(RedisTemplateredisTemplate) {        return redisTemplate.opsForList();    }    /**     * 对无序集合类型的数据操作     *     * @param redisTemplate     * @return     */    @Bean    public SetOperationssetOperations(RedisTemplateredisTemplate) {        return redisTemplate.opsForSet();    }    /**     * 对有序集合类型的数据操作     *     * @param redisTemplate     * @return     */    @Bean    public ZSetOperationszSetOperations(RedisTemplateredisTemplate) {        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";    } } 以上就是关于《阿里架构师分享:Redis短链接生成》的全部内容了,感兴趣的话可以点击右侧直接使用哦!》》在线短链接生成

相关推荐:

栏目分类

微商引流技巧网 www.yinliujiqiao.com 联系QQ:1716014443 邮箱:1716014443@qq.com

Copyright © 2019-2024 强大传媒 吉ICP备19000289号-9 网站地图 rss地图

Top