短鏈跳轉不再煩惱!SpringBoot 一鍵解決方案
在現代互聯網中,短鏈接作為一種高效的 URL 縮短和分享方式,被廣泛應用于社交媒體、電子郵件營銷以及各類平臺中。然而,如何實現短鏈接跳轉功能,同時確保系統的穩定性與高效性,成為開發者面臨的一項重要挑戰。
本篇文章將通過 SpringBoot 提供的一鍵解決方案,幫助開發者快速實現短鏈接跳轉功能。
短鏈跳轉的意義
用戶體驗優化
短鏈接長度短、外觀簡潔,能夠大幅提升用戶在鏈接分享與點擊過程中的體驗。
數據統計與跟蹤
通過短鏈接,可以有效追蹤鏈接的點擊情況,為營銷活動提供關鍵數據支持。
安全性與管理
短鏈接可以通過跳轉規則和權限控制,避免鏈接被濫用,并提升鏈接管理效率。
SpringBoot中的代碼實現
數據庫表設計
表結構保持不變:
CREATE TABLE url_map (
id BIGINTAUTO_INCREMENTPRIMARYKEY,
long_url VARCHAR(2083)NOTNULL,
short_url VARCHAR(255)NOTNULL,
username VARCHAR(255)NOTNULL,
expire_time DATETIME,
creation_time DATETIMEDEFAULTCURRENT_TIMESTAMP
);
SpringBoot中的代碼實現
利用 MyBatis-Plus 的注解,簡化實體類定義:
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.time.LocalDateTime;
@Data
@TableName("url_map")
public classUrlMap{
@TableId
private Long id;
private String longUrl;
private String shortUrl;
private String username;
private LocalDateTime expireTime;
private LocalDateTime creationTime;
}
Mapper 接口
MyBatis-Plus 自動生成 SQL,無需手動編寫 XML 映射文件:
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.icoderoad.entity.UrlMap;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface UrlMapMapper extends BaseMapper<UrlMap> {
}
服務層
服務層實現短鏈接生成和解析邏輯:
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.icoderoad.entity.UrlMap;
import com.icoderoad.mapper.UrlMapMapper;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDateTime;
@Service
public class UrlMapService{
@Resource
private UrlMapMapper urlMapMapper;
public Stringencode(String longUrl,String username){
QueryWrapper<UrlMap> queryWrapper =new QueryWrapper<>();
queryWrapper.eq("long_url", longUrl).eq("username", username);
UrlMap existingMap = urlMapMapper.selectOne(queryWrapper);
if(existingMap !=null){
return existingMap.getShortUrl();
}
String shortUrl =generateShortLink(longUrl, username);
UrlMap newMap = new UrlMap();
newMap.setLongUrl(longUrl);
newMap.setShortUrl(shortUrl);
newMap.setUsername(username);
newMap.setCreationTime(LocalDateTime.now());
urlMapMapper.insert(newMap);
return shortUrl;
}
public Stringdecode(String shortUrl){
QueryWrapper<UrlMap> queryWrapper =new QueryWrapper<>();
queryWrapper.eq("short_url", shortUrl);
UrlMap urlMap = urlMapMapper.selectOne(queryWrapper);
return urlMap !=null? urlMap.getLongUrl():"https://defaultpage.com";
}
private StringgenerateShortLink(String longUrl,String username){
try{
MessageDigest md =MessageDigest.getInstance("SHA-256");
byte[] hash = md.digest((longUrl + username).getBytes());
StringBuilder shortUrlBuilder =newStringBuilder();
for(byte b : hash){
shortUrlBuilder.append(String.format("%02x", b));
}
return shortUrlBuilder.substring(0,8);
}catch(NoSuchAlgorithmException e){
throw new RuntimeException("Error generating short link", e);
}
}
}
控制層
控制器提供 REST 接口:
import com.icoderoad.common.ResponseBean;
import com.icoderoad.service.UrlMapService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.view.RedirectView;
import javax.annotation.Resource;
@RestController
public class UrlMapController{
@Resource
private UrlMapService urlMapService;
@PostMapping("/shorten")
public ResponseBean<String> shorten(@RequestParamString longUrl,@RequestParamString username){
String shortUrl = urlMapService.encode(longUrl, username);
returnResponseBean.success(shortUrl);
}
@GetMapping("/redirect")
public RedirectViewredirect(@RequestParamString shortUrl){
String longUrl = urlMapService.decode(shortUrl);
return new RedirectView(longUrl);
}
}
返回結果類
返回結果的封裝類:
public class ResponseBean<T>{
private boolean success;
private T data;
public static<T> ResponseBean<T> success(T data){
ResponseBean<T> response =new ResponseBean<>();
response.success =true;
response.data = data;
return response;
}
public static<T>ResponseBean<T> error(){
ResponseBean<T> response =new ResponseBean<>();
response.success =false;
return response;
}
}
項目依賴
在 pom.xml 中添加 MyBatis-Plus 相關依賴:
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.3</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
結果測試
創建短鏈接
通過 Postman 或 cURL 發送 POST 請求,創建短鏈接:
使用 Postman 測試
1.設置請求類型為POST,請求地址為:
http://localhost:8080/shorten
2.在請求體中選擇 x-www-form-urlencoded,添加以下參數:
- longUrl: https://www.example.com
- username: test_user
3.點擊發送請求,響應示例如下:
{
"success": true,
"data": "http://localhost:8080/redirect?shortUrl=abcd1234"
}
使用 cURL 測試
運行以下命令:
curl -X POST http://localhost:8080/shorten \
-d "longUrl=https://www.example.com" \
-d "username=test_user"
響應:
{
"success": true,
"data": "http://localhost:8080/redirect?shortUrl=abcd1234"
}
短鏈接跳轉測試
測試步驟
1.在瀏覽器地址欄輸入生成的短鏈接,例如:
http://localhost:8080/redirect?shortUrl=abcd1234
2.按下回車鍵,瀏覽器將跳轉到原始鏈接:
https://www.example.com
響應驗證
通過 瀏覽器開發者工具 或 Postman,可以觀察 HTTP 重定向的響應頭,確認跳轉是否正確。例如:
HTTP/1.1 302 Found
Location: https://www.example.com
測試成功
當瀏覽器成功跳轉到 https://www.example.com 時,說明短鏈接跳轉功能正常工作。
總結
通過本文的講解,我們成功實現了一個基于 Spring Boot 的短鏈接服務,從短鏈接的生成到跳轉完成了全鏈路功能設計。在實現過程中,我們使用了 MyBatis-Plus 簡化數據訪問邏輯,通過精心設計的服務層確保了短鏈接的生成唯一性和效率。