感谢您的阅读,本文由 杨斌的博客 版权全部。
如若转载,请注明出处:杨斌的博客(https://y0ngb1n.github.io/a/b...)html
项目已托管于 GitHub:y0ngb1n/spring-boot-samples,欢迎 Star, Fork git
pom.xml
github
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>commons-validator</groupId> <artifactId>commons-validator</artifactId> </dependency> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> </dependency> </dependencies>
application.yml
web
spring: # Redis Config redis: url: 127.0.0.1 port: 6379 password: your_password logging: level: io.github.y0ngb1n.*: debug
/** * URL Shortener Resource * * @author yangbin */ @Slf4j @RestController @RequestMapping(path = "/v1") public class UrlShortenerController { @Autowired StringRedisTemplate redisTemplate; @GetMapping(path = "/{id}") public String getUrl(@PathVariable String id) { + String url = redisTemplate.opsForValue().get(id); log.debug("URL Retrieved: {}", url); return url; } @PostMapping public String create(@RequestBody String url) { UrlValidator urlValidator = new UrlValidator( new String[]{"http", "https"} ); if (urlValidator.isValid(url)) { - String id = Hashing.murmur3_32().hashString(url, StandardCharsets.UTF_8).toString(); log.debug("URL Id generated: {}", id); + redisTemplate.opsForValue().set(id, url); return id; } throw new RuntimeException("URL Invalid: " + url); } }
Step 0: 安装并启动 Redisredis
# on Windows scoop install redis redis-server # on Mac brew install redis redis-server
Step 1: 启动 url-shortener
服务spring
$ mvn install ... [INFO] BUILD SUCCESS ... $ mvn spring-boot:run ... 2019-08-21 21:03:50.215 INFO 10244 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path '' 2019-08-21 21:03:50.219 INFO 10244 --- [ main] i.g.y.s.u.UrlShortenerApplication : Started UrlShortenerApplication in 6.01 seconds (JVM running for 12.165)
Step 2: 生成短链缓存
$ curl -X POST http://127.0.0.1:8080/v1 \ -H 'Content-Type: text/plain' \ -d https://y0ngb1n.github.io 515bbe2b
Step 3: 还原短链tomcat
$ curl -X GET http://127.0.0.1:8080/v1/515bbe2b https://y0ngb1n.github.io
查看日志bash
... 2019-08-21 21:42:26.788 DEBUG 10244 --- [nio-8080-exec-2] i.g.y.s.u.c.UrlShortenerController : URL Id generated: 515bbe2b 2019-08-21 21:42:40.748 DEBUG 10244 --- [nio-8080-exec-3] i.g.y.s.u.c.UrlShortenerController : URL Retrieved: https://y0ngb1n.github.io
如何快速判断某 URL 是否在一个 20 亿的网址 URL 集合中?,by 张振伟app
黑名单
、URL 去重
、单词拼写检查
、Key-Value 缓存系统的 Key 校验
、ID 校验,好比订单系统查询某个订单 ID 是否存在,若是不存在就直接返回