为了生成唯一的短链接,我们可以利用UUID(通用唯一识别码)来确保每个短链接的唯一性。然后,我们将这个UUID进行Base62编码以缩短其长度。以下是完整的Spring Boot应用程序示例,展示了如何实现这一功能。
1. 添加依赖
首先,在你的pom.xml
文件中添加必要的依赖项:
<dependencies><!-- Spring Web --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!-- H2 Database for simplicity --><dependency><groupId>com.h2database</groupId><artifactId>h2</artifactId><scope>runtime</scope></dependency><!-- JPA --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jpa</artifactId></dependency>
</dependencies>
2. 创建实体类
创建一个名为ShortLink
的实体类,用于映射数据库中的表:
java">import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;@Entity
public class ShortLink {@Id@GeneratedValue(strategy = GenerationType.IDENTITY)private Long id;private String originalUrl;private String shortCode;// Getters and Setterspublic Long getId() {return id;}public void setId(Long id) {this.id = id;}public String getOriginalUrl() {return originalUrl;}public void setOriginalUrl(String originalUrl) {this.originalUrl = originalUrl;}public String getShortCode() {return shortCode;}public void setShortCode(String shortCode) {this.shortCode = shortCode;}
}
3. 创建Repository
创建一个JpaRepository接口来处理数据库操作:
java">import org.springframework.data.jpa.repository.JpaRepository;public interface ShortLinkRepository extends JpaRepository<ShortLink, Long> {ShortLink findByShortCode(String shortCode);boolean existsByShortCode(String shortCode);
}
4. 创建Service
创建一个服务类来处理业务逻辑:
java">import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import java.util.UUID;@Service
public class ShortLinkService {@Autowiredprivate ShortLinkRepository repository;public String generateShortLink(String originalUrl) {String shortCode = encodeUUIDToBase62(UUID.randomUUID());ShortLink link = new ShortLink();link.setOriginalUrl(originalUrl);link.setShortCode(shortCode);repository.save(link);return shortCode;}public String redirect(String shortCode) {ShortLink link = repository.findByShortCode(shortCode);if (link != null) {return link.getOriginalUrl();} else {throw new RuntimeException("Invalid URL");}}private String encodeUUIDToBase62(UUID uuid) {long mostSignificantBits = uuid.getMostSignificantBits();long leastSignificantBits = uuid.getLeastSignificantBits();StringBuilder base62String = new StringBuilder();base62String.append(encodeLongToBase62(mostSignificantBits));base62String.append(encodeLongToBase62(leastSignificantBits));return base62String.toString().substring(0, 8); // Take first 8 characters for shorter links}private static final String BASE62_CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";private String encodeLongToBase62(long value) {StringBuilder base62String = new StringBuilder();do {int index = (int) (value % BASE62_CHARACTERS.length());base62String.insert(0, BASE62_CHARACTERS.charAt(index));value /= BASE62_CHARACTERS.length();} while (value > 0);return base62String.toString();}
}
5. 创建Controller
创建一个控制器来处理HTTP请求:
java">import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;@RestController
@RequestMapping("/api")
public class ShortLinkController {@Autowiredprivate ShortLinkService service;@PostMapping("/shorten")public String shorten(@RequestParam String url) {return service.generateShortLink(url);}@GetMapping("/{code}")public String redirectToOriginalUrl(@PathVariable String code) {return "redirect:" + service.redirect(code);}
}
6. 配置文件
最后,在application.properties
中配置H2数据库:
# DataSource Configuration
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password# Hibernate Properties
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect
完整项目结构
src/main/java/com/example/demo/
├── DemoApplication.java
├── controller/
│ └── ShortLinkController.java
├── entity/
│ └── ShortLink.java
├── repository/
│ └── ShortLinkRepository.java
└── service/└── ShortLinkService.java
主应用程序类
确保你有一个主应用程序类来启动Spring Boot应用:
java">package com.example.demo;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
public class DemoApplication {public static void main(String[] args) {SpringApplication.run(DemoApplication.class, args);}
}
现在,你可以启动这个Spring Boot应用程序,并使用提供的API来生成短链接以及通过短链接重定向到原始URL。UUID结合Base62编码可以有效地生成唯一的、较短的短链接。