Coder Social home page Coder Social logo

imdaya / shorturl Goto Github PK

View Code? Open in Web Editor NEW

This project forked from naccl/shorturl

0.0 1.0 0.0 1.16 MB

长链接生成短链接/短网址,访问短链接重定向至长链接 https://d.naccl.top

Home Page: https://d.naccl.top

License: MIT License

Java 67.14% CSS 20.82% HTML 12.04%

shorturl's Introduction

短链接服务

长链接生成短链接,访问短链接 302 重定向至原始长链接

依赖 说明
Spring Boot MVC 框架
thymeleaf 模板引擎
MyBatis ORM 框架
Redis 缓存
hutool Hash 算法、布隆过滤器

实现

使用 MurmurHash 算法将原始长链接 hash 为 32 位散列值,将散列值转为 62 进制字符串,即为短链接,将短链接添加入布隆过滤器,并向 Redis 添加指定过期时间的缓存。用户访问短链接,在 Redis 中查找是否存在缓存,存在则延长缓存时间;不存在,查找数据库并添加缓存,302 重定向至原始长链接,并自增短链接访问量。

技术选型

MurmurHash:长链转短链自然需要一个哈希算法,应用的类型决定了我们并不需要解密,而是关心运算速度和冲突概率,MurmurHash 就是一种非加密型哈希算法,与 MD5、SHA 等常见哈希函数相比,性能与随机分布特征都要更佳。MurmurHash 有 32 bit、64 bit、128 bit 的实现,32 bit 已经足够表示近 43 亿个短链接。使用 Java 的话,在 Google 的 guavahutool 中有相应实现,这里使用 hutool。

base62:MurmurHash 生成的哈希值最长有 10 位十进制数,为了进一步缩短短链接长度,可以将哈希值转为 62 进制,最长为 6 个字符。

布隆过滤器:哈希函数不可避免会产生哈希冲突,随着短链接越来越多,冲突概率也会越大。每次生成短链接后,向布隆过滤器中查找是否已经存在此短链接,如果已经存在,则在长链接后添加一个自定义字符串,重新 hash,重复上一步,直到没有哈希冲突,把短链接加入布隆过滤器。这里使用 hutool 工具包中基于 JVM 的布隆过滤器来实现。

Redis:生成短链接后,通常在后续一段时间内此短链接的使用频率较高,则向 Redis 中添加带过期时间的缓存来减轻数据库压力。

302 状态码:301 为永久重定向、302 为临时重定向,通常需要记录短链接访问次数或需要修改、删除短链接时,使用 302 临时重定向来处理,和服务器压力相比,数据的价值往往更大。

shorturl's People

Contributors

naccl avatar

Watchers

James Cloos avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.