Skip to content

Commit

Permalink
Merge pull request #42 from nastiausenko/feature/original-link-redirect
Browse files Browse the repository at this point in the history
Add caching for short links in redirect controller
  • Loading branch information
IvanShalaev1990 authored Apr 17, 2024
2 parents 8f3d79c + dfd3d2e commit 8980db8
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 5 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package com.linkurlshorter.urlshortener.redirect;

import com.linkurlshorter.urlshortener.link.Link;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
@RequiredArgsConstructor
public class LinkCache {

private final Map<String, Link> cache = new HashMap<>();

public boolean containsShortLink(String shortLink) {
return cache.containsKey(shortLink);
}

public Link getByShortLink(String shortLink) {
return cache.get(shortLink);
}

public void putLink(String shortLink, Link link) {
cache.put(shortLink, link);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -32,23 +32,35 @@ public class LinkRedirectController {
*/
private final LinkService linkService;

private final LinkCache linkCache;

/**
* Redirects a request with a short link to its corresponding long link.
*
* @param shortLink the short link to be redirected
* @return a RedirectView object directing the user to the long link
*/
@GetMapping("/{shortLink}")
public RedirectView redirectToLongLink(@PathVariable("shortLink") String shortLink) {
Link link = linkService.findByShortLink(shortLink);
public RedirectView redirectToOriginalLink(@PathVariable("shortLink") String shortLink) {
Link link = linkCache.containsShortLink(shortLink)
? linkCache.getByShortLink(shortLink)
: linkService.findByShortLink(shortLink);

updateLinkStats(link);
return redirectToLongLink(link);
}

private void updateLinkStats(Link link) {
link.setStatistics(link.getStatistics() + 1);
link.setExpirationTime(LocalDateTime.now().plusMonths(1));
linkService.save(link);

String longLink = link.getLongLink();
linkService.update(link);
linkCache.putLink(link.getShortLink(), link);
}

private RedirectView redirectToLongLink(Link link) {
RedirectView redirectView = new RedirectView();
redirectView.setUrl(longLink);
redirectView.setUrl(link.getLongLink());
redirectView.setStatusCode(HttpStatusCode.valueOf(302));
return redirectView;
}
Expand Down

0 comments on commit 8980db8

Please sign in to comment.