简单的方案是使用uuid生成, 但太长且数据库检索效率低。
本次使用hashIds的方案 简单 安全。
简述
网上有很多提供短链接服务的网站
提供下思路:
将长链接存储到db中,该条数据对应一个自增id。
短链接为 http://shortService.cn/s/01
后台则可查出id为1的长连接 并重定向到其网址上
但参数之间时/s/number
显然不太好
所以对数字id用hashids加密
除了用hashids的方式加密,也可将数字转为62进制的方式 实现简单加密
代码
maven坐标
1
2
3
4
5
|
<dependency>
<groupId>org.hashids</groupId>
<artifactId>hashids</artifactId>
<version>1.0.3</version>
</dependency>
|
代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
|
import org.hashids.Hashids;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
class UrlShort {
// 本例中原始链接存放在内存中,如真正作为服务则应持久化存储
public static void main(String[] args) {
String veryLongUrl = "http://www.baidu.com/aaaaaaaaaaaaaaa/bbbbbbbbbb/ccccccccc";
UrlShort urlShortService = new UrlShort();
// 对长链接进行缩短处理
String shortCode = urlShortService.add(veryLongUrl);
String shortUrl = "http://myshorUrl.com/s/" + shortCode;
System.out.println("获得短链接-" + shortUrl);
// 当有人访问了短链接后 则解析shortCode
String realUrl = urlShortService.read(shortCode);
System.out.println("http-302-重定向到原网址-" + realUrl);
}
ConcurrentHashMap db = new ConcurrentHashMap<Long, String>();
AtomicLong idGenerator = new AtomicLong();
Hashids hashids;
public UrlShort() {
String salt = "short url salt";
int minHashLength = 3;
String alphabet = "abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ23456789";
this.hashids = new Hashids(salt, minHashLength, alphabet);
}
String add(String url) {
long newId = idGenerator.incrementAndGet();
db.put(newId, url);
String shortCode = hashids.encode(newId);
return shortCode;
}
String read(String code) {
long[] decode = hashids.decode(code);
if (decode == null) {
throw new RuntimeException("无效的短链接");
}
String realUrl = (String) db.get(decode[0]);
return realUrl;
}
}
|
运行后结果
1
2
|
获得短链接-http://myshorUrl.com/s/Da8
http-302-重定向到原网址-http://www.baidu.com/aaaaaaaaaaaaaaa/bbbbbbbbbb/ccccccccc
|
文章作者
duansheli
上次更新
2019-12-25
(325c7b3)