SpringBootストレージサーバの開発

15886 ワード

今日はSpring BootのAngular統合を試み、フロントエンドレンダリングプログラミング言語としてAngularを使用してフロントエンドページレンダリングを行う非常に簡単なSpring Bootマイクロサービスを構築することにした.
きそかんきょう
ぎじゅつ
バージョン#バージョン#
Java
1.8+
SpringBoot
1.5.x
プロジェクトの作成
  • 初期化項目
  • mvn archetype:generate -DgroupId=com.edurt.sli.sliss -DartifactId=spring-learn-integration-springboot-storage -DarchetypeArtifactId=maven-archetype-quickstart -Dversion=1.0.0 -DinteractiveMode=false
  • pomを修正する.xml javaとspringbootのサポート
  • を追加
    
    
    
        
            spring-learn-integration-springboot
            com.edurt.sli
            1.0.0
        
    
        4.0.0
    
        spring-learn-integration-springboot-storage
    
        SpringBoot       
    
        
            
                org.springframework.boot
                spring-boot-starter-web
            
        
    
        
            
                
                    org.springframework.boot
                    spring-boot-maven-plugin
                    ${dependency.springboot.version}
                    
                        true
                    
                
                
                    org.apache.maven.plugins
                    maven-compiler-plugin
                    ${plugin.maven.compiler.version}
                    
                        ${system.java.version}
                        ${system.java.version}
                    
                
            
        
    
    
  • 単純なアプリケーションクラス
  • /**
     * Licensed to the Apache Software Foundation (ASF) under one
     * or more contributor license agreements.  See the NOTICE file
     * distributed with this work for additional information
     * regarding copyright ownership.  The ASF licenses this file
     * to you under the Apache License, Version 2.0 (the
     * "License"); you may not use this file except in compliance
     * with the License.  You may obtain a copy of the License at
     * 

    * http://www.apache.org/licenses/LICENSE-2.0 *

    * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.edurt.sli.sliss; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** *

    SpringBootStorageIntegration

    *

    Description : SpringBootStorageIntegration

    *

    Author : qianmoQ

    *

    Version : 1.0

    *

    Create Time : 2019-06-10 15:53

    *

    Author Email: qianmoQ

    */ @SpringBootApplication public class SpringBootStorageIntegration { public static void main(String[] args) { SpringApplication.run(SpringBootStorageIntegration.class, args); } }
    Rest APIインタフェース機能の追加(アップロードサービス提供)
  • controllerフォルダを作成し、そのフォルダの下にUploadController Rest APIインタフェースを作成します.簡単なファイルアップロードインタフェース
  • を提供します.
    /**
     * Licensed to the Apache Software Foundation (ASF) under one
     * or more contributor license agreements.  See the NOTICE file
     * distributed with this work for additional information
     * regarding copyright ownership.  The ASF licenses this file
     * to you under the Apache License, Version 2.0 (the
     * "License"); you may not use this file except in compliance
     * with the License.  You may obtain a copy of the License at
     * 

    * http://www.apache.org/licenses/LICENSE-2.0 *

    * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.edurt.sli.sliss.controller; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; /** *

    UploadController

    *

    Description : UploadController

    *

    Author : qianmoQ

    *

    Version : 1.0

    *

    Create Time : 2019-06-10 15:55

    *

    Author Email: qianmoQ

    */ @RestController @RequestMapping(value = "upload") public class UploadController { // private final static String UPLOADED_FOLDER = "/Users/shicheng/Desktop/test/"; @PostMapping public String upload(@RequestParam("file") MultipartFile file) { if (file.isEmpty()) { return " "; } try { byte[] bytes = file.getBytes(); Path path = Paths.get(UPLOADED_FOLDER + file.getOriginalFilename()); Files.write(path, bytes); return " "; } catch (IOException ioe) { return " , : " + ioe.getMessage(); } } @GetMapping public Object get() { File file = new File(UPLOADED_FOLDER); String[] filelist = file.list(); return filelist; } @DeleteMapping public String delete(@RequestParam(value = "file") String file) { File source = new File(UPLOADED_FOLDER + file); source.delete(); return " " + file + " "; } }
  • SpringBootAngularIntegrationクラスファイルを変更Controller
  • をスキャンするために、次の設定スキャンパスを追加します.
    /**
     * Licensed to the Apache Software Foundation (ASF) under one
     * or more contributor license agreements.  See the NOTICE file
     * distributed with this work for additional information
     * regarding copyright ownership.  The ASF licenses this file
     * to you under the Apache License, Version 2.0 (the
     * "License"); you may not use this file except in compliance
     * with the License.  You may obtain a copy of the License at
     * 

    * http://www.apache.org/licenses/LICENSE-2.0 *

    * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.edurt.sli.sliss; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ComponentScan; /** *

    SpringBootStorageIntegration

    *

    Description : SpringBootStorageIntegration

    *

    Author : qianmoQ

    *

    Version : 1.0

    *

    Create Time : 2019-06-10 15:53

    *

    Author Email: qianmoQ

    */ @SpringBootApplication @ComponentScan(value = { "com.edurt.sli.sliss.controller" }) public class SpringBootStorageIntegration { public static void main(String[] args) { SpringApplication.run(SpringBootStorageIntegration.class, args); } }
    サービスを開始し、APIインタフェースの可用性をテスト
    コンパイラでSpringBootStorageIntegrationクラスファイルを直接起動するか、jarをパッケージして起動し、パッケージコマンドmvn clean package
  • アップロードファイルインタフェース
  • をテストする
    curl localhost:8080/upload -F "file=@/Users/shicheng/Downloads/qrcode/qrcode_for_ambari.jpg"
    結果を返す
          
  • クエリーファイルインタフェース
  • をテストする
    curl localhost:8080/upload
    結果を返す
    ["qrcode_for_ambari.jpg"]
  • テスト削除インタフェース
  • curl -X DELETE 'localhost:8080/upload?file=qrcode_for_ambari.jpg'
    結果を返す
        qrcode_for_ambari.jpg  
    ファイルが削除されたかどうかを再確認
    curl localhost:8080/upload
    結果を返す
    []
    ダウンロードファイルのサポートを追加
  • controllerフォルダの下にDownloadController Rest APIインタフェースを作成します.ファイルダウンロードインタフェース
  • を提供します.
    /**
     * Licensed to the Apache Software Foundation (ASF) under one
     * or more contributor license agreements.  See the NOTICE file
     * distributed with this work for additional information
     * regarding copyright ownership.  The ASF licenses this file
     * to you under the Apache License, Version 2.0 (the
     * "License"); you may not use this file except in compliance
     * with the License.  You may obtain a copy of the License at
     * 

    * http://www.apache.org/licenses/LICENSE-2.0 *

    * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.edurt.sli.sliss.controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletResponse; import java.io.*; /** *

    DownloadController

    *

    Description : DownloadController

    *

    Author : qianmoQ

    *

    Version : 1.0

    *

    Create Time : 2019-06-10 16:21

    *

    Author Email: qianmoQ

    */ @RestController @RequestMapping(value = "download") public class DownloadController { private final static String UPLOADED_FOLDER = "/Users/shicheng/Desktop/test/"; @GetMapping public String download(@RequestParam(value = "file") String file, HttpServletResponse response) { if (!file.isEmpty()) { File source = new File(UPLOADED_FOLDER + file); if (source.exists()) { response.setContentType("application/force-download");// response.addHeader("Content-Disposition", "attachment;fileName=" + file);// byte[] buffer = new byte[1024]; FileInputStream fileInputStream = null; BufferedInputStream bufferedInputStream = null; try { fileInputStream = new FileInputStream(source); bufferedInputStream = new BufferedInputStream(fileInputStream); OutputStream outputStream = response.getOutputStream(); int i = bufferedInputStream.read(buffer); while (i != -1) { outputStream.write(buffer, 0, i); i = bufferedInputStream.read(buffer); } return " "; } catch (Exception e) { e.printStackTrace(); } finally { if (bufferedInputStream != null) { try { bufferedInputStream.close(); } catch (IOException e) { return " , : " + e.getMessage(); } } if (fileInputStream != null) { try { fileInputStream.close(); } catch (IOException e) { return " , : " + e.getMessage(); } } } } } return " "; } }
  • テストダウンロードファイル
  • curl -o a.jpg 'localhost:8080/download?file=qrcode_for_ambari.jpg'
    次のプログレスバーが表示されます.
      % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                     Dload  Upload   Total   Spent    Left  Speed
    100  148k    0  148k    0     0  11.3M      0 --:--:-- --:--:-- --:--:-- 12.0M
    ローカルフォルダにダウンロードするかどうかを問い合わせる
    ls a.jpg
    結果を返す
    a.jpg
    ファイルサイズの設定
    Spring Bootの最大ファイルアップロードサイズはデフォルトで1 MBです.次のアプリケーションのプロパティで値を設定できます.
  • プロファイル
  • #http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#common-application-properties
    #search multipart
    spring.http.multipart.max-file-size=10MB
    spring.http.multipart.max-request-size=10MB
  • コード構成、configフォルダを作成し、そのフォルダの下にMultipartConfig
  • を作成する
    /**
     * Licensed to the Apache Software Foundation (ASF) under one
     * or more contributor license agreements.  See the NOTICE file
     * distributed with this work for additional information
     * regarding copyright ownership.  The ASF licenses this file
     * to you under the Apache License, Version 2.0 (the
     * "License"); you may not use this file except in compliance
     * with the License.  You may obtain a copy of the License at
     * 

    * http://www.apache.org/licenses/LICENSE-2.0 *

    * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.edurt.sli.sliss.config; import org.springframework.boot.web.servlet.MultipartConfigFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import javax.servlet.MultipartConfigElement; /** *

    MultipartConfig

    *

    Description : MultipartConfig

    *

    Author : qianmoQ

    *

    Version : 1.0

    *

    Create Time : 2019-06-10 16:34

    *

    Author Email: qianmoQ

    */ @Configuration public class MultipartConfig { @Bean public MultipartConfigElement multipartConfigElement() { MultipartConfigFactory factory = new MultipartConfigFactory(); factory.setMaxFileSize("10240KB"); //KB,MB factory.setMaxRequestSize("102400KB"); return factory.createMultipartConfig(); } }
    パッケージファイルの配置
  • パッケージングデータ
  • mvn clean package -Dmaven.test.skip=true -X
    パッケージされたファイルの実行
    java -jar target/spring-learn-integration-springboot-storage-1.0.0.jar
    ソースアドレス
  • GitHub
  • Gitee