SpringBoot开发存储服务器实现过程详解

目录
  • 正文
    • 基础环境
    • 创建项目
    • 添加Rest API接口功能(提供上传服务)
    • 启动服务,测试API接口可用性
    • 增加下载文件支持
    • 文件大小设置
    • 打包文件部署

正文

今天我们尝试Spring Boot整合Angular,并决定建立一个非常简单的Spring Boot微服务,使用Angular作为前端渲编程语言进行前端页面渲染.

基础环境

技术 版本
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的支持
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>spring-learn-integration-springboot</artifactId>
        <groupId>com.edurt.sli</groupId>
        <version>1.0.0</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <artifactId>spring-learn-integration-springboot-storage</artifactId>
    <name>SpringBoot开发存储服务器</name>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>${dependency.springboot.version}</version>
                <configuration>
                    <fork>true</fork>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>${plugin.maven.compiler.version}</version>
                <configuration>
                    <source>${system.java.version}</source>
                    <target>${system.java.version}</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
  • 一个简单的应用类
/**
 * 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
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * 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;
/**
 * <p> SpringBootStorageIntegration </p>
 * <p> Description : SpringBootStorageIntegration </p>
 * <p> Author : qianmoQ </p>
 * <p> Version : 1.0 </p>
 * <p> Create Time : 2019-06-10 15:53 </p>
 * <p> Author Email: <a href="mailTo:shichengoooo@163.com" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow" >qianmoQ</a> </p>
 */
@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
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * 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;
/**
 * <p> UploadController </p>
 * <p> Description : UploadController </p>
 * <p> Author : qianmoQ </p>
 * <p> Version : 1.0 </p>
 * <p> Create Time : 2019-06-10 15:55 </p>
 * <p> Author Email: <a href="mailTo:shichengoooo@163.com" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow" >qianmoQ</a> </p>
 */
@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
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * 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;
/**
 * <p> SpringBootStorageIntegration </p>
 * <p> Description : SpringBootStorageIntegration </p>
 * <p> Author : qianmoQ </p>
 * <p> Version : 1.0 </p>
 * <p> Create Time : 2019-06-10 15:53 </p>
 * <p> Author Email: <a href="mailTo:shichengoooo@163.com" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow" >qianmoQ</a> </p>
 */
@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
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * 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.*;
/**
 * <p> DownloadController </p>
 * <p> Description : DownloadController </p>
 * <p> Author : qianmoQ </p>
 * <p> Version : 1.0 </p>
 * <p> Create Time : 2019-06-10 16:21 </p>
 * <p> Author Email: <a href="mailTo:shichengoooo@163.com" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow" >qianmoQ</a> </p>
 */
@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最大文件上传大小为1MB,您可以通过以下应用程序属性配置值:

  • 配置文件
#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
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * 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;
/**
 * <p> MultipartConfig </p>
 * <p> Description : MultipartConfig </p>
 * <p> Author : qianmoQ </p>
 * <p> Version : 1.0 </p>
 * <p> Create Time : 2019-06-10 16:34 </p>
 * <p> Author Email: <a href="mailTo:shichengoooo@163.com" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow" >qianmoQ</a> </p>
 */
@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

以上就是SpringBoot开发存储服务器实现过程详解的详细内容,更多关于SpringBoot 存储服务器的资料请关注我们其它相关文章!

(0)

相关推荐

  • SpringBoot整合Graylog做日志收集实现过程

    目录 日志收集折腾过程 ELK EFK ELFK 自己撸一个 Graylog 环境搭建 创建输入 Spring Boot整合Graylog 总结 日志收集折腾过程 ELK 之前整合过ELK做日志采集,就是Elasticsearch + Logstash + Kibana: Elasticsearch:存储引擎,存放日志内容,利于全文检索 Logstash:数据传输管道,将日志内容传输到Elasticsearch,并且支持过滤内容,将内容格式化后再传输,可以满足绝大部分的应用场景 Kibana:开

  • 大厂禁止SpringBoot在项目使用Tomcat容器原理解析

    目录 前言 SpringBoot中的Tomcat容器 SpringBoot设置Undertow Tomcat与Undertow的优劣对比 最后 前言 在SpringBoot框架中,我们使用最多的是Tomcat,这是SpringBoot默认的容器技术,而且是内嵌式的Tomcat.同时,SpringBoot也支持Undertow容器,我们可以很方便的用Undertow替换Tomcat,而Undertow的性能和内存使用方面都优于Tomcat,那我们如何使用Undertow技术呢?本文将为大家细细讲解

  • SpringBoot数据库初始化datasource配置方式

    目录 I. 项目搭建 1. 依赖 2. 配置 3. 初始化sql II. 示例 1. 验证demo 2. 问题记录 2.1 只有初始化数据data.sql,没有schema.sql时,不生效 2.2 版本问题导致配置不生效 2.3 mode配置不对导致不生效 2.4 重复启动之后,报错 小结 I. 项目搭建 在我们的日常业务开发过程中,如果有db的相关操作,通常我们是直接建立好对应的库表结构,并初始化对应的数据,即更常见的情况下是我们在已有表结构基础之下,进行开发: 但是当我们是以项目形式工作时

  • SpringBoot定时任务设计之时间轮案例原理详解

    目录 知识准备 什么是时间轮(Timing Wheel) Netty的HashedWheelTimer要解决什么问题 HashedWheelTimer的使用方式 实现案例 Pom依赖 2个简单例子 HashedWheelTimer是如何实现的? 什么是多级Timing Wheel? 知识准备 Timer和ScheduledExecutorService是JDK内置的定时任务方案,而业内还有一个经典的定时任务的设计叫时间轮(Timing Wheel), Netty内部基于时间轮实现了一个Hashe

  • Springboot FatJa原理机制源码解析

    目录 一.概述 二.标准的 jar 包结构 三.探索JarLauncher 3.1 只能拷贝出来一份儿 3.2 携带程序所依赖的jar而非仅class 四. 自定义类加载器的运行机制 4.1 指定资源 4.2 创建自定义 ClassLoader 4.3 设置线程上下文类加载器,调用程序中的 main class 一.概述 SpringBoot FatJar 的设计,打破了标准 jar 的结构,在 jar 包内携带了其所依赖的 jar 包,通过 jar 中的 main 方法创建自己的类加载器,来识

  • SpringBoot 容器刷新前回调ApplicationContextInitializer

    目录 引言 I. 项目准备 II. 容器刷新前扩展点实例 1. 自定义ApplicationContextInitializer 2. 扩展点注册 3. 执行顺序指定 4. 使用场景示例 5. 小结 III. 不能错过的源码和相关知识点 项目 引言 本文将作为Spring系列教程中源码版块的第一篇,整个源码系列将分为两部分进行介绍:单纯的源码解析,大概率是个吃力没人看的事情,因此我们将结合源码解析,一个是学习下别人的优秀设计,一个是站在源码的角度看一下我们除了日常的CURD之外,还可以干些啥 在

  • SpringBoot开发存储服务器实现过程详解

    目录 正文 基础环境 创建项目 添加Rest API接口功能(提供上传服务) 启动服务,测试API接口可用性 增加下载文件支持 文件大小设置 打包文件部署 正文 今天我们尝试Spring Boot整合Angular,并决定建立一个非常简单的Spring Boot微服务,使用Angular作为前端渲编程语言进行前端页面渲染. 基础环境 技术 版本 Java 1.8+ SpringBoot 1.5.x 创建项目 初始化项目 mvn archetype:generate -DgroupId=com.e

  • SpringBoot整合Druid数据源过程详解

    这篇文章主要介绍了SpringBoot整合Druid数据源过程详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 1.数据库结构 2.项目结构 3.pom.xml文件 <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</ar

  • 轻松搞定SpringBoot JPA使用配置过程详解

    SpringBoot整合JPA 使用数据库是开发基本应用的基础,借助于开发框架,我们已经不用编写原始的访问数据库的代码,也不用调用JDBC(Java Data Base Connectivity)或者连接池等诸如此类的被称作底层的代码,我们将从更高的层次上访问数据库,这在Springboot中更是如此,本章我们将详细介绍在Springboot中使用 Spring Data JPA 来实现对数据库的操作. JPA & Spring Data JPA JPA是Java Persistence API

  • Django 开发环境配置过程详解

    开发环境 开发环境为: Win 10(64位) Python 3.7.0 Django 2.1 安装Python python的安装为比较简单,首先找到Python官方网站,选择python3.7的windows版本,下载并安装. 安装时注意勾选添加python到环境变量中.如果没有或者漏掉这一步,请安装完毕后自行添加. 若实在不知道怎么弄的,看这篇文章: windows上安装python3教程以及环境变量配置 安装完成后打开命令行,输入python -V,系统打印出python的版本号,说明安

  • 使用apifm-wxapi快速开发小程序过程详解

    前言 我们要开发小程序,基本上都要涉及到以下几个方面的工作: 1.购买服务器,用来运行后台及接口程序: 2.购买域名,小程序中需要通过域名来调用服务器的数据: 3.购买 SSL 证书,小程序强制需要 https 的地址,传统无证书不加密的 http 请求微信不支持: 4.后台程序员开发后台程序,这样才能登录后台进行商品管理.订单维护.资金财务管理等等: 5.后台程序员开发小程序可用的 restfull api 接口或者是 websocket 接口: 6.开发的后台及接口程序的安全性.功能性.稳定

  • SpringBoot登录验证码实现过程详解

    今天记录一下验证码的实现,希望能够帮助到大家! 首先我们看一下实现的效果: 此验证码的实现没有用到太多的插件,话不多说直接上代码,大家拿过去就可以用. 中间用到了org.apache.commons.lang3.RandomUtils工具类,需要pom配置: <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 --> <dependency> <groupId>org.apac

  • SpringBoot JPA使用配置过程详解

    JPA是什么? JPA(Java Persistence API)是Sun官方提出的Java持久化规范. 为Java开发人员提供了一种对象/关联映射工具来管理Java应用中的关系数据. 它的出现是为了简化现有的持久化开发工作和整合ORM技术. 结束各个ORM框架各自为营的局面. JPA 其实是一种规范,它的实现中比较出名的是 Hibernate 框架: 1.pom 引入依赖: <dependency> <groupId>org.springframework.boot</gr

  • SpringBoot整合FastDFS方法过程详解

    一.pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM

  • Prometheus开发中间件Exporter过程详解

    Prometheus 为开发这提供了客户端工具,用于为自己的中间件开发Exporter,对接Prometheus . 目前支持的客户端 Go Java Python Ruby 以go为例开发自己的Exporter 依赖包的引入 工程结构 [root@node1 data]# tree exporter/ exporter/ ├── collector │ └── node.go ├── go.mod └── main.go 引入依赖包 require ( github.com/modern-go

  • springboot整合shiro的过程详解

    目录 什么是 Shiro Shiro 架构 Shiro 架构图 Shiro 工作原理 Shiro 详细架构图 springboot 整合 shiro springboot 整合 shiro 思路 项目搭建 主要依赖 数据库表设计 实体类 自定义 Realm shiro 的配置类 ShiroFilterFactoryBean 过滤器链配置中的 url 匹配规则 ShiroFilterFactoryBean 过滤器 ShiroFilterFactoryBean 过滤器分类 前端页面 登录页面 log

随机推荐