Browse Source

09 02 01 全院损益计算关于全院损益计算的问题

hr 4 years ago
parent
commit
a1cf475d90

+ 7 - 0
pom.xml

@@ -174,6 +174,13 @@
             <version>3.16</version>
         </dependency>
 
+        <!--minio文件服务-->
+        <dependency>
+            <groupId>io.minio</groupId>
+            <artifactId>minio</artifactId>
+            <version>7.0.2</version>
+        </dependency>
+
     </dependencies>
 
     <build>

+ 44 - 0
src/main/java/com/imed/costaccount/common/file/MinioConfig.java

@@ -0,0 +1,44 @@
+package com.imed.costaccount.common.file;
+
+import io.minio.MinioClient;
+import io.minio.errors.InvalidEndpointException;
+import io.minio.errors.InvalidPortException;
+import lombok.Data;
+import org.springframework.boot.context.properties.ConfigurationProperties;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+
+/**
+ * url: http://118.31.245.65:9000/
+ * access-key: admin
+ * secret-key: xywl2021701
+ * bucket-name: test
+ */
+
+/**
+ * @Component 每次返回的对象不同 类似于多例 用于解决全局变量不一致的问题
+ * @Configuration 每次从spring容器中获取保证每次都是同一个实例对象 类似单例
+ */
+@Configuration
+@Data
+@ConfigurationProperties(prefix = "minio")
+public class MinioConfig {
+
+    private String url;
+
+    private Integer port;
+
+    private String accessKey;
+
+    private String secretKey;
+
+    private String bucketName;
+
+
+    @Bean
+    public MinioClient minioClient() throws InvalidPortException, InvalidEndpointException {
+        MinioClient minioClient = new MinioClient(url, port, accessKey, secretKey, bucketName, false);
+        return minioClient;
+    }
+
+}

+ 404 - 0
src/main/java/com/imed/costaccount/common/file/MinioFileUtil.java

@@ -0,0 +1,404 @@
+package com.imed.costaccount.common.file;
+
+import cn.hutool.core.io.IoUtil;
+import cn.hutool.core.util.StrUtil;
+import io.minio.MinioClient;
+import io.minio.ObjectStat;
+import io.minio.PutObjectOptions;
+import io.minio.Result;
+import io.minio.errors.InvalidExpiresRangeException;
+import io.minio.messages.Bucket;
+import io.minio.messages.DeleteError;
+import io.minio.messages.Item;
+import lombok.SneakyThrows;
+import org.springframework.context.annotation.Configuration;
+
+import javax.servlet.http.HttpServletResponse;
+import java.io.InputStream;
+import java.net.URLEncoder;
+import java.util.ArrayList;
+import java.util.List;
+
+
+/**
+ * 仅作为开发文件上传下载使用,生产环境待定选择文件服务器.......
+ * 使用minio上传文件相关工具类
+ */
+@Configuration
+public class MinioFileUtil {
+
+    private final MinioClient minioClient;
+    private static final Integer DEFAULT_EXPIRY_TIME = 7 * 24 * 60 * 60;
+
+
+    public MinioFileUtil(MinioClient minioClient) {
+        this.minioClient = minioClient;
+    }
+
+    /**
+     * 检查存储桶是否存在
+     *
+     * @param bucketName 存储桶名称
+     * @return
+     */
+    @SneakyThrows
+    public boolean bucketExists(String bucketName) {
+        boolean flag = minioClient.bucketExists(bucketName);
+        if (flag) {
+            return true;
+        }
+        return false;
+    }
+
+    /**
+     * 创建存储桶
+     *
+     * @param bucketName 存储桶名称
+     */
+    @SneakyThrows
+    public boolean makeBucket(String bucketName) {
+        boolean flag = bucketExists(bucketName);
+        if (!flag) {
+            minioClient.makeBucket(bucketName);
+            return true;
+        } else {
+            return false;
+        }
+    }
+
+    /**
+     * 列出所有存储桶名称
+     *
+     * @return
+     */
+    @SneakyThrows
+    public List<String> listBucketNames()  {
+        List<Bucket> bucketList = listBuckets();
+        List<String> bucketListName = new ArrayList<>();
+        for (Bucket bucket : bucketList) {
+            bucketListName.add(bucket.name());
+        }
+        return bucketListName;
+    }
+
+    /**
+     * 列出所有存储桶
+     *
+
+     */
+    @SneakyThrows
+    public List<Bucket> listBuckets() {
+        return minioClient.listBuckets();
+    }
+
+    /**
+     * 删除存储桶
+     *
+     * @param bucketName 存储桶名称
+     * @return
+     */
+    @SneakyThrows
+    public boolean removeBucket(String bucketName) {
+        boolean flag = bucketExists(bucketName);
+        if (flag) {
+            Iterable<Result<Item>> myObjects = listObjects(bucketName);
+            for (Result<Item> result : myObjects) {
+                Item item = result.get();
+                // 有对象文件,则删除失败
+                if (item.size() > 0) {
+                    return false;
+                }
+            }
+            // 删除存储桶,注意,只有存储桶为空时才能删除成功。
+            minioClient.removeBucket(bucketName);
+            flag = bucketExists(bucketName);
+            if (!flag) {
+                return true;
+            }
+
+        }
+        return false;
+    }
+
+    /**
+     * 列出存储桶中的所有对象名称
+     *
+     * @param bucketName 存储桶名称
+     * @return
+     */
+    @SneakyThrows
+    public List<String> listObjectNames(String bucketName)  {
+        List<String> listObjectNames = new ArrayList<>();
+        boolean flag = bucketExists(bucketName);
+        if (flag) {
+            Iterable<Result<Item>> myObjects = listObjects(bucketName);
+            for (Result<Item> result : myObjects) {
+                Item item = result.get();
+                listObjectNames.add(item.objectName());
+            }
+        }
+        return listObjectNames;
+    }
+
+    /**
+     * 列出存储桶中的所有对象
+     *
+     * @param bucketName 存储桶名称
+     * @return
+     */
+    @SneakyThrows
+    public Iterable<Result<Item>> listObjects(String bucketName)  {
+        boolean flag = bucketExists(bucketName);
+        if (flag) {
+            return minioClient.listObjects(bucketName);
+        }
+        return null;
+    }
+
+    /**
+     * 通过文件上传到对象
+     *
+     * @param bucketName 存储桶名称
+     * @param objectName 存储桶里的对象名称 ( 可以理解为path)
+     * @param fileName   File name
+     */
+    @SneakyThrows
+    public boolean putObject(String bucketName, String objectName, String fileName){
+        boolean flag = bucketExists(bucketName);
+        if (flag) {
+            minioClient.putObject(bucketName, objectName, fileName, null);
+            ObjectStat statObject = statObject(bucketName, objectName);
+            if (statObject != null && statObject.length() > 0) {
+                return true;
+            }
+        }
+        return false;
+
+    }
+
+    /**
+     * 通过InputStream上传对象
+     *
+     * @param bucketName 存储桶名称
+     * @param objectName 存储桶里的对象名称 (path + 加上文件名)
+     * @param stream     要上传的流
+     * @return
+     */
+    @SneakyThrows
+    public boolean putObject(String bucketName, String objectName, InputStream stream) {
+        boolean flag = bucketExists(bucketName);
+        if (flag) {
+            minioClient.putObject(bucketName, objectName, stream, new PutObjectOptions(stream.available(), -1));
+            ObjectStat statObject = statObject(bucketName, objectName);
+            if (statObject != null && statObject.length() > 0) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    /**
+     * 以流的形式获取一个文件对象
+     *
+     * @param bucketName 存储桶名称
+     * @param objectName 存储桶里的对象名称
+     * @return
+     */
+    @SneakyThrows
+    public InputStream getObject(String bucketName, String objectName) {
+        boolean flag = bucketExists(bucketName);
+        if (flag) {
+            ObjectStat statObject = statObject(bucketName, objectName);
+            if (statObject != null && statObject.length() > 0) {
+                InputStream stream = minioClient.getObject(bucketName, objectName);
+                return stream;
+            }
+        }
+        return null;
+    }
+
+    /**
+     * 以流的形式获取一个文件对象(断点下载)
+     *
+     * @param bucketName 存储桶名称
+     * @param objectName 存储桶里的对象名称
+     * @param offset     起始字节的位置
+     * @param length     要读取的长度 (可选,如果无值则代表读到文件结尾)
+     * @return
+     */
+    @SneakyThrows
+    public InputStream getObject(String bucketName, String objectName, long offset, Long length) {
+        boolean flag = bucketExists(bucketName);
+        if (flag) {
+            ObjectStat statObject = statObject(bucketName, objectName);
+            if (statObject != null && statObject.length() > 0) {
+                InputStream stream = minioClient.getObject(bucketName, objectName, offset, length);
+                return stream;
+            }
+        }
+        return null;
+    }
+
+    /**
+     * 下载并将文件保存到本地
+     *
+     * @param bucketName 存储桶名称
+     * @param objectName 存储桶里的对象名称
+     * @param fileName   File name
+     * @return
+     */
+    @SneakyThrows
+    public boolean getObject(String bucketName, String objectName, String fileName) {
+        boolean flag = bucketExists(bucketName);
+        if (flag) {
+            ObjectStat statObject = statObject(bucketName, objectName);
+            if (statObject != null && statObject.length() > 0) {
+                minioClient.getObject(bucketName, objectName, fileName);
+                return true;
+            }
+        }
+        return false;
+    }
+
+    /**
+     * 删除一个对象
+     *
+     * @param bucketName 存储桶名称
+     * @param objectName 存储桶里的对象名称
+     */
+    @SneakyThrows
+    public boolean removeObject(String bucketName, String objectName) {
+        boolean flag = bucketExists(bucketName);
+        if (flag) {
+            minioClient.removeObject(bucketName, objectName);
+            return true;
+        }
+        return false;
+
+    }
+
+    /**
+     * 删除指定桶的多个文件对象,返回删除错误的对象列表,全部删除成功,返回空列表
+     *
+     * @param bucketName  存储桶名称
+     * @param objectNames 含有要删除的多个object名称的迭代器对象
+     * @return
+     */
+    @SneakyThrows
+    public List<String> removeObject(String bucketName, List<String> objectNames) {
+        List<String> deleteErrorNames = new ArrayList<>();
+        boolean flag = bucketExists(bucketName);
+        if (flag) {
+            Iterable<Result<DeleteError>> results = minioClient.removeObjects(bucketName, objectNames);
+            for (Result<DeleteError> result : results) {
+                DeleteError error = result.get();
+                deleteErrorNames.add(error.objectName());
+            }
+        }
+        return deleteErrorNames;
+    }
+
+    /**
+     * 生成一个给HTTP GET请求用的presigned URL。
+     * 浏览器/移动端的客户端可以用这个URL进行下载,即使其所在的存储桶是私有的。这个presigned URL可以设置一个失效时间,默认值是7天。
+     *
+     * @param bucketName 存储桶名称
+     * @param objectName 存储桶里的对象名称
+     * @param expires    失效时间(以秒为单位),默认是7天,不得大于七天
+     * @return
+     */
+    @SneakyThrows
+    public String presignedGetObject(String bucketName, String objectName, Integer expires) {
+        boolean flag = bucketExists(bucketName);
+        String url = "";
+        if (flag) {
+            if (expires < 1 || expires > DEFAULT_EXPIRY_TIME) {
+                throw new InvalidExpiresRangeException(expires,
+                        "expires must be in range of 1 to " + DEFAULT_EXPIRY_TIME);
+            }
+            url = minioClient.presignedGetObject(bucketName, objectName, expires);
+        }
+        return url;
+    }
+
+    /**
+     * 生成一个给HTTP PUT请求用的presigned URL。
+     * 浏览器/移动端的客户端可以用这个URL进行上传,即使其所在的存储桶是私有的。这个presigned URL可以设置一个失效时间,默认值是7天。
+     *
+     * @param bucketName 存储桶名称
+     * @param objectName 存储桶里的对象名称
+     * @param expires    失效时间(以秒为单位),默认是7天,不得大于七天
+     * @return
+     */
+    @SneakyThrows
+    public String presignedPutObject(String bucketName, String objectName, Integer expires) {
+        boolean flag = bucketExists(bucketName);
+        String url = "";
+        if (flag) {
+            if (expires < 1 || expires > DEFAULT_EXPIRY_TIME) {
+                throw new InvalidExpiresRangeException(expires,
+                        "expires must be in range of 1 to " + DEFAULT_EXPIRY_TIME);
+            }
+            url = minioClient.presignedPutObject(bucketName, objectName, expires);
+        }
+        return url;
+    }
+
+    /**
+     * 获取对象的元数据
+     *
+     * @param bucketName 存储桶名称
+     * @param objectName 存储桶里的对象名称
+     * @return
+     */
+    @SneakyThrows
+    public ObjectStat statObject(String bucketName, String objectName) {
+        boolean flag = bucketExists(bucketName);
+        if (flag) {
+            ObjectStat statObject = minioClient.statObject(bucketName, objectName);
+            return statObject;
+        }
+        return null;
+    }
+
+    /**
+     * 文件访问路径
+     *
+     * @param bucketName 存储桶名称
+     * @param objectName 存储桶里的对象名称
+     * @return
+     */
+    @SneakyThrows
+    public String getObjectUrl(String bucketName, String objectName) {
+        boolean flag = bucketExists(bucketName);
+        String url = "";
+        if (flag) {
+            url = minioClient.getObjectUrl(bucketName, objectName);
+        }
+        return url;
+    }
+
+    /**
+     * 下载文件
+     * @param bucketName 存储空间名
+     * @param fileName 文件名(带上个path)
+     * @param response HttpServletResponse
+     */
+    @SneakyThrows
+    public void download(String bucketName, String fileName, HttpServletResponse response) {
+        //获取对象信息和对象的元数据。
+        ObjectStat objectStat = statObject(bucketName, fileName);
+        //setContentType 设置发送到客户机的响应的内容类型
+        response.setContentType(objectStat.contentType());
+        //设置响应头
+        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(objectStat.name(), "UTF-8"));
+        //文件流
+        InputStream object = getObject(bucketName, fileName);
+        //设置文件大小
+        response.setHeader("Content-Length", String.valueOf(objectStat.length()));
+        IoUtil.copy(object, response.getOutputStream());
+        //关闭流
+        object.close();
+    }
+
+}

+ 1 - 1
src/main/java/com/imed/costaccount/common/shiro/ShiroConfig.java

@@ -42,7 +42,7 @@ public class ShiroConfig {
         filterMap.put("/v2/api-docs", "anon");
         filterMap.put("/swagger-ui.html", "anon");
         filterMap.put("/static/js/**", "anon");
-        filterMap.put("/demo", "anon");
+        filterMap.put("/demo/**", "anon");
         filterMap.put("/doc.html", "anon");
         filterMap.put("/**/*.xlsx", "anon");
         filterMap.put("/**/*.xls", "anon");

+ 66 - 4
src/main/java/com/imed/costaccount/web/DemoController.java

@@ -1,19 +1,41 @@
 package com.imed.costaccount.web;
 
+import cn.hutool.core.date.DatePattern;
+import cn.hutool.core.date.DateTime;
+import cn.hutool.core.date.DateUtil;
+import cn.hutool.core.io.IoUtil;
+import cn.hutool.core.lang.UUID;
+import com.imed.costaccount.common.exception.CostException;
+import com.imed.costaccount.common.file.MinioFileUtil;
 import com.imed.costaccount.common.util.Result;
 import com.imed.costaccount.service.DemoService;
-import org.springframework.web.bind.annotation.GetMapping;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RestController;
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiOperation;
+import lombok.SneakyThrows;
+import lombok.var;
+import org.springframework.web.bind.annotation.*;
+import org.springframework.web.multipart.MultipartFile;
 
+import javax.servlet.ServletOutputStream;
+import javax.servlet.http.HttpServletResponse;
+import java.io.BufferedInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.PrintWriter;
+
+@Api(tags = "demo")
 @RestController
 @RequestMapping("/demo")
 public class DemoController {
 
+    private static final String bucketName = "test";
+    private static final Long hospId = 777L;
     private final DemoService demoService;
+    private final MinioFileUtil fileUtil;
 
-    public DemoController(DemoService demoService) {
+    public DemoController(DemoService demoService, MinioFileUtil fileUtil) {
         this.demoService = demoService;
+        this.fileUtil = fileUtil;
     }
 
 
@@ -22,4 +44,44 @@ public class DemoController {
         demoService.test();
         return Result.ok();
     }
+
+    @ApiOperation("upload")
+    @PostMapping("/upload")
+    public Result ok(@RequestParam("file") MultipartFile file) {
+        DateTime date = DateUtil.date();
+        int month = DateUtil.month(date) + 1;
+        int year = DateUtil.year(date);
+        int day = DateUtil.dayOfMonth(date);
+        try {
+            // 文件唯一性处理(根据业务需求处理)
+            String format = DateUtil.format(date, DatePattern.PURE_DATETIME_PATTERN);
+            String originalFilename = format+file.getOriginalFilename();
+            String fileName = hospId + "/" + year + "/" + month + "/" + day + "/" + originalFilename;
+            InputStream inputStream = file.getInputStream();
+            fileUtil.putObject(bucketName, fileName, inputStream);
+            String objectUrl = fileUtil.getObjectUrl(bucketName, fileName);
+            return Result.ok(objectUrl);
+        } catch (IOException e) {
+            throw new CostException("文件错误");
+        }
+    }
+
+    @SneakyThrows
+    @ApiOperation("download")
+    @GetMapping("/download")
+    public void download(HttpServletResponse response) {
+        // 方式1
+        fileUtil.download(bucketName, "777/2021/9/2/minmin.jpg", response);
+
+        // 方式2
+//        InputStream object = fileUtil.getObject(bucketName, "777/2021/9/2/minmin.jpg");
+//        response.setContentType("application/octet-stream;charset=UTF-8");
+//        response.setHeader("Content-disposition", "attachment;filename=minmin.jpg");
+//        ServletOutputStream out = response.getOutputStream();
+//        IoUtil.copy(object, out);
+//        IoUtil.close(out);
+//        IoUtil.close(object);
+
+    }
+
 }

+ 8 - 0
src/main/resources/application.yml

@@ -28,3 +28,11 @@ cost:
   jwt:
     secret: 12321312asdsdsfdfsd
     expire: 100000
+
+minio:
+  url: http://118.31.245.65
+  port: 9000
+  access-key: admin
+  secret-key: xywl2021701
+  bucket-name: test
+