springboot中縮短一個url鏈接的實現
縮短 URL 是現代應用程序中常見的需求,通常用于減少長 URL 的長度,使其更易于分享。URL 縮短服務的核心思路是將長 URL 映射到一個唯一的短代碼。較為復雜的場景可能涉及多種功能,例如:
- 縮短的 URL 自動過期(即在一定時間后失效)。
- 統計 URL 的訪問量。
- 檢查并避免短 URL 重復。
- 添加安全機制,如防止惡意鏈接。
場景案例
我們可以設計一個場景:
- 用戶通過 API 提交長 URL。
- 系統生成短 URL,短 URL 有有效期(例如 7 天),并存儲在數據庫中。
- 用戶可以通過 API 查詢短 URL 的訪問次數。
- 每當有人訪問短 URL,系統會記錄訪問量,并自動重定向到原始的長 URL。
- 在短 URL 過期后,無法再進行重定向。
技術棧
- Spring Boot: 用于快速構建 RESTful API 服務。
- H2 數據庫: 用于存儲 URL 和相關元數據。
- Java UUID: 生成唯一短碼。
- Java 定時任務: 自動清理過期 URL。
Step 1: 項目結構
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 以及相關元數據的實體類。
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)建一個操作數據庫的接口。
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 重定向、統計訪問量等。
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 數據庫以及其他 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。
總結
通過 Spring Boot 框架,我們可以快速構建一個帶有定時任務、訪問統計以及過期處理的 URL 縮短服務。在真實場景中,可能還會涉及更多的功能,如用戶身份驗證、URL 黑名單過濾等。
到此這篇關于springboot中縮短一個url鏈接的實現的文章就介紹到這了,更多相關springboot縮短url鏈接內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
springboot+springJdbc+postgresql 實現多數據源的配置
本文主要介紹了springboot+springJdbc+postgresql 實現多數據源的配置,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-09-09
Spring?Boot?中的?@HystrixCommand?注解原理及使用方法
通過使用 @HystrixCommand 注解,我們可以輕松地實現對方法的隔離和監(jiān)控,從而提高系統的可靠性和穩(wěn)定性,本文介紹了Spring Boot 中的@HystrixCommand注解是什么,其原理以及如何使用,感興趣的朋友跟隨小編一起看看吧2023-07-07
SpringDataRedis入門和序列化方式解決內存占用問題小結
spring-data-redis是spring-data模塊的一部分,專門用來支持在spring管理項目對redis的操作,這篇文章主要介紹了SpringDataRedis入門和序列化方式解決內存占用問題,需要的朋友可以參考下2022-12-12
MyBatis使用resultMap如何解決列名和屬性名不一致
這篇文章主要介紹了MyBatis使用resultMap如何解決列名和屬性名不一致的問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-01-01
SpringBoot使用Quartz無法注入Bean的問題及解決
這篇文章主要介紹了SpringBoot使用Quartz無法注入Bean的問題及解決方案,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-11-11

