日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > java >内容正文

java

Java中的42行代码中的URL缩短服务— Java(?!)Spring Boot + Redis

發布時間:2023/12/3 java 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Java中的42行代码中的URL缩短服务— Java(?!)Spring Boot + Redis 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

顯然,編寫URL縮短服務是新的“ Hello,world! ”在IoT /微服務/時代的世界中。 一切始于在45行Scala中的URL縮短服務 -整潔的Scala,以Spray和Redis進行調味以進行存儲。 隨后, 在35行Clojure中使用了url縮短服務,在 Haskell的43行中使用了URL縮短器 。 所以我內心的反時髦人士問:用Java語言要花多長時間? 但是,出于善意,不是普通的Java。 帶有Spring Data Redis的 Spring Boot是一個很好的起點。 我們需要的只是一個處理GET和POST的簡單控制器:

import com.google.common.hash.Hashing; import org.apache.commons.validator.routines.UrlValidator; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.http.*; import org.springframework.web.bind.annotation.*;import javax.servlet.http.*; import java.nio.charset.StandardCharsets;@org.springframework.boot.autoconfigure.EnableAutoConfiguration @org.springframework.stereotype.Controller public class UrlShortener {public static void main(String[] args) {SpringApplication.run(UrlShortener.class, args);}@Autowired private StringRedisTemplate redis;@RequestMapping(value = "/{id}", method = RequestMethod.GET)public void redirect(@PathVariable String id, HttpServletResponse resp) throws Exception {final String url = redis.opsForValue().get(id);if (url != null)resp.sendRedirect(url);elseresp.sendError(HttpServletResponse.SC_NOT_FOUND);}@RequestMapping(method = RequestMethod.POST)public ResponseEntity<String> save(HttpServletRequest req) {final String queryParams = (req.getQueryString() != null) ? "?" + req.getQueryString() : "";final String url = (req.getRequestURI() + queryParams).substring(1);final UrlValidator urlValidator = new UrlValidator(new String[]{"http", "https"});if (urlValidator.isValid(url)) {final String id = Hashing.murmur3_32().hashString(url, StandardCharsets.UTF_8).toString();redis.opsForValue().set(id, url);return new ResponseEntity<>("http://mydomain.com/" + id, HttpStatus.OK);} elsereturn new ResponseEntity<>(HttpStatus.BAD_REQUEST);} }

該代碼很好地自我描述,并且在功能上等同于Scala中的版本。 我沒有試圖太擠它以使行數盡可能的短,上面的代碼很典型,只包含很少的細節:

  • 我通常不使用通配符導入
  • 我不使用完全限定的類名(我想保存一條import行,我承認)
  • 我用if括號包圍if else用括號括起來
  • 我幾乎從不使用場注入,這是控制家族反轉中最丑陋的兄弟。 相反,我會去讓構造函數允許使用模擬的Redis進行測試:
@Autowired private final StringRedisTemplate redis;public UrlShortener(StringRedisTemplate redis) {this.redis = redis; }

我最苦惱的事情是……獲取原始的完整URL。 基本上,我需要.com或port之后的所有內容。 沒有流血的方式(既沒有servlet,也沒有Spring MVC),因此笨拙的getQueryString()擺弄著。 您可以按以下方式使用該服務-創建較短的URL:

$ curl -vX POST localhost:8080/https://www.google.pl/search?q=tomasz+nurkiewicz> POST /https://www.google.pl/search?q=tomasz+nurkiewicz HTTP/1.1 > User-Agent: curl/7.30.0 > Host: localhost:8080 > Accept: */* > < HTTP/1.1 200 OK < Server: Apache-Coyote/1.1 < Content-Type: text/plain;charset=ISO-8859-1 < Content-Length: 28 < Date: Sat, 23 Aug 2014 20:47:40 GMT < http://mydomain.com/50784f51

通過較短的網址重定向:

$ curl -v localhost:8080/50784f51> GET /50784f51 HTTP/1.1 > User-Agent: curl/7.30.0 > Host: localhost:8080 > Accept: */* > < HTTP/1.1 302 Found < Server: Apache-Coyote/1.1 < Location: https://www.google.pl/search?q=tomasz+nurkiewicz < Content-Length: 0 < Date: Sat, 23 Aug 2014 20:48:00 GMT <

為了完整起見,這是Gradle中的一個構建文件(maven也可以使用),在所有先前的解決方案中都跳過了:

buildscript {repositories {mavenLocal()maven { url "http://repo.spring.io/libs-snapshot" }mavenCentral()}dependencies {classpath 'org.springframework.boot:spring-boot-gradle-plugin:1.1.5.RELEASE'} }apply plugin: 'java' apply plugin: 'spring-boot'sourceCompatibility = '1.8'repositories {mavenLocal()maven { url 'http://repository.codehaus.org' }maven { url 'http://repo.spring.io/milestone' }mavenCentral() }dependencies {compile "org.springframework.boot:spring-boot-starter-web:1.1.5.RELEASE"compile "org.springframework.boot:spring-boot-starter-redis:1.1.5.RELEASE"compile 'com.google.guava:guava:17.0'compile 'org.apache.commons:commons-lang3:3.3.2'compile 'commons-validator:commons-validator:1.4.0'compile 'org.apache.tomcat.embed:tomcat-embed-el:8.0.9'compile "org.aspectj:aspectjrt:1.8.1"runtime "cglib:cglib-nodep:3.1" }tasks.withType(GroovyCompile) {groovyOptions.optimizationOptions.indy = true }task wrapper(type: Wrapper) {gradleVersion = '2.0' }

實際上也是42行...這就是整個應用程序,沒有XML,沒有描述符,沒有安裝。

對于最短,最模糊的工作代碼,我不認為此練習只是一個虛擬的代碼。 帶有Redis后端的URL縮短器Web服務是給定語言和生態系統的語法和功能的有趣展示。 有趣的是,還有很多算法問題,例如在Rosetta代碼中發現的。 這也是編寫REST服務的一個很好的基本模板。

原始Scala實現的一個重要功能(包括該實現)在所有實現中都以某種方式被默默地忘記了,它是非阻塞的。 HTTP和Redis的訪問是事件驅動的( 反應 ,沒事,我說),所以我想它可以同時處理客戶數以萬計。 阻止由Tomcat支持的控制器無法實現這一點。 但是,您仍然必須承認,用Java(甚至不是Java 8!)編寫的這種服務簡明扼要,易于遵循和簡單明了-其他解決方案都不是可讀的(當然這是主觀的)。

等待別人!

翻譯自: https://www.javacodegeeks.com/2014/08/url-shortener-service-in-42-lines-of-code-in-java-spring-boot-redis.html

總結

以上是生活随笔為你收集整理的Java中的42行代码中的URL缩短服务— Java(?!)Spring Boot + Redis的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。