利用 Spring Boot & Redis 實現短連接服務

感謝您的閱讀,本文由 楊斌的博客 版權全部。
如若轉載,請註明出處:楊斌的博客(y0ngb1n.github.io/a/build-a-c…html

項目已託管於 GitHub:y0ngb1n/spring-boot-samples,歡迎 Star, Fork 😘git


準備工做

  • Spring Boot 2.1.0+
  • Redis
  • Lombok
  • Guava 28.0
  • Common Validator 1.6

添加依賴項

pom.xmlgithub

<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.ymlweb

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
複製代碼

參考資料

相關文章
相關標籤/搜索