내 세상

[Spring] URL Shorten 서비스 개발 본문

Technical/Spring

[Spring] URL Shorten 서비스 개발

sga8 2021. 6. 23. 13:16
728x90
반응형

 

Base62

- 문자나 일반 데이터를 Base 62 색인표를 기반으로 인코딩하는 방식.

- Base64에서 62번째(+), 63번째(/) 기호는 url에서 parameter로 사용할 수 없기 때문에, 제외한 것.

- cf) Base64 Url Safe 버전이 있음. ( +(plus) 기호 → -(minus)기호, /(divide) 기호 → _(underline) 기호 )

 

랜덤성을 위해 base62 문자열 위치 변경

AS-IS: abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ

TO-BE: aZbYc0XdWeV1fUgTh2SiRjQ3kPlOm4NnMoL5pKqJr6IsHtG7uFvEw8DxCyB9zA

@Service
public class Base62 {	private static final char[] BASE62 = "aZbYc0XdWeV1fUgTh2SiRjQ3kPlOm4NnMoL5pKqJr6IsHtG7uFvEw8DxCyB9zA".toCharArray();

	private int abs(int a) {
		return a > 0 ? a : -a;
	}

	public String encode(int id) {
		StringBuilder shortURL = new StringBuilder("");
		while (id > 0) {
			shortURL.append(BASE62[id % 62]);
			id /= 62;
		}
		return shortURL.reverse().toString();
	}

	public int decode(String str) {
		int id = 0;
		for (int i = 0; i < str.length(); i++) {
			char ch = str.charAt(i);
			if ('a' <= ch && ch <= 'z') {
				id = id * 62 + ((ch - 'a') * 2) * 6 / 5;
			} else if ('A' <= ch && ch <= 'Z') {
				id = id * 62 + ((abs(ch - 'Z') + 1) * 2 - 1) * 6 / 5;
			} else if ('0' <= ch && ch <= '9') {
				id = id * 62 + (ch - '0') * 6 + 5;
			}
		}
		return id;
	}
}

 

Original URL -> Short URL

	public UrlShortener shortenUrl(String originUrl) {
		String shortUrl;
		UrlShortener urlShortener = urlShortenerMapper.findUrlShortenerByOriginUrl(originUrl);
		if (urlShortener != null) {
			shortUrl = ShortenerConstants.ShortenerPrefix + base62.encode(urlShortener.getId());
			urlShortener.setCount(urlShortener.getCount() + 1);
			urlShortenerMapper.updateUrlShortener(urlShortener);
			urlShortener.setShortUrl(shortUrl);
			return urlShortener;
		}

		UrlShortener newUrlShortener = new UrlShortener(0, originUrl);
		urlShortenerMapper.createUrlShortener(newUrlShortener);
		shortUrl = ShortenerConstants.ShortenerPrefix
				+ base62.encode(urlShortenerMapper.findUrlShortenerByOriginUrl(originUrl).getId());
		newUrlShortener.setShortUrl(shortUrl);
		return newUrlShortener;
	}

 

 

Short URL -> Original URL

	public String restoreOriginUrl(Map<String, Object> map) {
		return restoreOriginUrl(map.get(ShortenerConstants.KEY_SHORTURL).toString());
	}

	public String restoreOriginUrl(String shortUrl) {
		int id = base62.decode(shortUrl);
		UrlShortener result = urlShortenerMapper.findUrlShortenerById(id);
		if (result == null)
			return null;
		return result.getOriginUrl();
	}

 

728x90
반응형