springboot中縮短一個url鏈接的實現(xiàn)
縮短 URL 是現(xiàn)代應用程序中常見的需求,通常用于減少長 URL 的長度,使其更易于分享。URL 縮短服務的核心思路是將長 URL 映射到一個唯一的短代碼。較為復雜的場景可能涉及多種功能,例如:
- 縮短的 URL 自動過期(即在一定時間后失效)。
- 統(tǒng)計 URL 的訪問量。
- 檢查并避免短 URL 重復。
- 添加安全機制,如防止惡意鏈接。
場景案例
我們可以設計一個場景:
- 用戶通過 API 提交長 URL。
- 系統(tǒng)生成短 URL,短 URL 有有效期(例如 7 天),并存儲在數(shù)據(jù)庫中。
- 用戶可以通過 API 查詢短 URL 的訪問次數(shù)。
- 每當有人訪問短 URL,系統(tǒng)會記錄訪問量,并自動重定向到原始的長 URL。
- 在短 URL 過期后,無法再進行重定向。
技術棧
- Spring Boot: 用于快速構建 RESTful API 服務。
- H2 數(shù)據(jù)庫: 用于存儲 URL 和相關元數(shù)據(jù)。
- Java UUID: 生成唯一短碼。
- Java 定時任務: 自動清理過期 URL。
Step 1: 項目結(jié)構
src/ ├── main/ │ ├── java/ │ │ └── com/ │ │ └── example/ │ │ ├── UrlShortenerApplication.java │ │ ├── controller/ │ │ │ └── UrlController.java │ │ ├── model/ │ │ │ └── Url.java │ │ ├── repository/ │ │ │ └── UrlRepository.java │ │ └── service/ │ │ └── UrlService.java │ └── resources/ │ └── application.properties
Step 2: 創(chuàng)建實體類 Url
Url.java 是用于存儲長 URL、短 URL 以及相關元數(shù)據(jù)的實體類。
package com.example.model;
import javax.persistence.*;
import java.time.LocalDateTime;
@Entity
public class Url {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String originalUrl;
private String shortCode;
private LocalDateTime createdAt;
private LocalDateTime expiresAt;
private int visitCount;
public Url() {}
public Url(String originalUrl, String shortCode, LocalDateTime createdAt, LocalDateTime expiresAt) {
this.originalUrl = originalUrl;
this.shortCode = shortCode;
this.createdAt = createdAt;
this.expiresAt = expiresAt;
this.visitCount = 0;
}
// getters and setters
}Step 3: 創(chuàng)建 Repository 接口
使用 Spring Data JPA,我們可以快速創(chuàng)建一個操作數(shù)據(jù)庫的接口。
package com.example.repository;
import com.example.model.Url;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.Optional;
public interface UrlRepository extends JpaRepository<Url, Long> {
Optional<Url> findByShortCode(String shortCode);
void deleteByExpiresAtBefore(LocalDateTime dateTime);
}Step 4: 編寫服務類 UrlService
UrlService.java 包含業(yè)務邏輯,例如生成短 URL、處理 URL 重定向、統(tǒng)計訪問量等。
package com.example.service;
import com.example.model.Url;
import com.example.repository.UrlRepository;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.Optional;
import java.util.UUID;
@Service
public class UrlService {
private final UrlRepository urlRepository;
public UrlService(UrlRepository urlRepository) {
this.urlRepository = urlRepository;
}
public String shortenUrl(String originalUrl, int expirationDays) {
String shortCode = UUID.randomUUID().toString().substring(0, 8); // 生成短碼
LocalDateTime createdAt = LocalDateTime.now();
LocalDateTime expiresAt = createdAt.plusDays(expirationDays);
Url url = new Url(originalUrl, shortCode, createdAt, expiresAt);
urlRepository.save(url);
return shortCode;
}
public Optional<Url> getOriginalUrl(String shortCode) {
Optional<Url> urlOptional = urlRepository.findByShortCode(shortCode);
urlOptional.ifPresent(url -> {
if (url.getExpiresAt().isAfter(LocalDateTime.now())) {
url.setVisitCount(url.getVisitCount() + 1);
urlRepository.save(url);
}
});
return urlOptional.filter(url -> url.getExpiresAt().isAfter(LocalDateTime.now()));
}
public int getVisitCount(String shortCode) {
return urlRepository.findByShortCode(shortCode)
.map(Url::getVisitCount)
.orElse(0);
}
// 定時任務清理過期 URL
public void cleanUpExpiredUrls() {
urlRepository.deleteByExpiresAtBefore(LocalDateTime.now());
}
}Step 5: 編寫 Controller
UrlController.java 是與前端或其他客戶端交互的層。
package com.example.controller;
import com.example.model.Url;
import com.example.service.UrlService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.Optional;
@RestController
@RequestMapping("/api/url")
public class UrlController {
private final UrlService urlService;
public UrlController(UrlService urlService) {
this.urlService = urlService;
}
@PostMapping("/shorten")
public ResponseEntity<String> shortenUrl(@RequestParam String originalUrl, @RequestParam(defaultValue = "7") int expirationDays) {
String shortCode = urlService.shortenUrl(originalUrl, expirationDays);
return ResponseEntity.ok("Shortened URL: http://localhost:8080/api/url/" + shortCode);
}
@GetMapping("/{shortCode}")
public ResponseEntity<?> redirectUrl(@PathVariable String shortCode) {
Optional<Url> urlOptional = urlService.getOriginalUrl(shortCode);
return urlOptional
.map(url -> ResponseEntity.status(302).header("Location", url.getOriginalUrl()).build())
.orElse(ResponseEntity.notFound().build());
}
@GetMapping("/{shortCode}/stats")
public ResponseEntity<Integer> getUrlStats(@PathVariable String shortCode) {
int visitCount = urlService.getVisitCount(shortCode);
return ResponseEntity.ok(visitCount);
}
}Step 6: 定時清理任務
Spring Boot 可以通過 @Scheduled 注解定期執(zhí)行任務。我們可以創(chuàng)建一個任務來清理過期的 URL。
package com.example.service;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class CleanupTask {
private final UrlService urlService;
public CleanupTask(UrlService urlService) {
this.urlService = urlService;
}
@Scheduled(cron = "0 0 0 * * ?") // 每天午夜執(zhí)行一次
public void cleanExpiredUrls() {
urlService.cleanUpExpiredUrls();
}
}Step 7: 配置文件
在 application.properties 中配置 H2 數(shù)據(jù)庫以及其他 Spring Boot 配置。
spring.datasource.url=jdbc:h2:mem:testdb spring.datasource.driverClassName=org.h2.Driver spring.datasource.username=sa spring.datasource.password=password spring.h2.console.enabled=true spring.jpa.hibernate.ddl-auto=update
Step 8: 啟動類 UrlShortenerApplication.java
package com.example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableScheduling
public class UrlShortenerApplication {
public static void main(String[] args) {
SpringApplication.run(UrlShortenerApplication.class, args);
}
}運行服務
- 使用 POST 請求 /api/url/shorten 提交長 URL 并獲取短 URL。
- 使用 GET 請求 /api/url/{shortCode} 重定向到原始 URL。
- 使用 GET 請求 /api/url/{shortCode}/stats 獲取短 URL 的訪問量。
- 每天定時任務會清理過期的 URL。
總結(jié)
通過 Spring Boot 框架,我們可以快速構建一個帶有定時任務、訪問統(tǒng)計以及過期處理的 URL 縮短服務。在真實場景中,可能還會涉及更多的功能,如用戶身份驗證、URL 黑名單過濾等。
到此這篇關于springboot中縮短一個url鏈接的實現(xiàn)的文章就介紹到這了,更多相關springboot縮短url鏈接內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Java設計模式之策略模式_動力節(jié)點Java學院整理
策略模式是對算法的封裝,把一系列的算法分別封裝到對應的類中,并且這些類實現(xiàn)相同的接口,相互之間可以替換。接下來通過本文給大家分享Java設計模式之策略模式,感興趣的朋友一起看看吧2017-08-08
Logback 使用TurboFilter實現(xiàn)日志級別等內(nèi)容的動態(tài)修改操作
這篇文章主要介紹了Logback 使用TurboFilter實現(xiàn)日志級別等內(nèi)容的動態(tài)修改操作,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-08-08
spring-boot中使用spring-boot-devtools的實現(xiàn)代碼
這篇文章主要介紹了spring-boot中使用spring-boot-devtools的實現(xiàn)代碼,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-11-11
Java中BeanUtils.copyProperties()詳解及應用場景
BeanUtils.copyProperties()是Apache?Commons?BeanUtils提供的方法,用于Java對象間屬性的復制,特別適用于DTO、VO和Entity之間的數(shù)據(jù)傳遞,這篇文章主要介紹了Java中BeanUtils.copyProperties()詳解及應用場景的相關資料,需要的朋友可以參考下2024-09-09

