nahida před 1 rokem
revize
056cbcbdb0

+ 50 - 0
.gitignore

@@ -0,0 +1,50 @@
+
+# .gitignore
+# Bytecode files
+*.class
+
+# IntelliJ IDEA
+.idea/
+*.iml
+*.iws
+*.ipr
+
+# Eclipse
+.classpath
+.project
+.settings/
+bin/
+target/
+
+# Maven
+target/
+pom.xml.tag
+pom.xml.releaseBackup
+pom.xml.versionsBackup
+release.properties
+dependency-reduced-pom.xml
+
+# Visual Studio Code
+.vscode/
+
+# OS generated files #
+.DS_Store
+.DS_Store?
+._*
+.Spotlight-V100
+.Trashes
+
+# Environment variables file
+.env
+
+# Logs
+logs/
+*.log
+
+# Runtime data
+*.run
+
+# Spring Boot
+build/
+*.jar
+*.war

+ 41 - 0
pom.xml

@@ -0,0 +1,41 @@
+<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">
+    <modelVersion>4.0.0</modelVersion>
+    <parent>
+        <groupId>com.zksy</groupId>
+        <artifactId>zksy</artifactId>
+        <version>1.0.0</version>
+    </parent>
+
+    <artifactId>minioutil</artifactId>
+    <packaging>jar</packaging>
+
+    <name>minioutil</name>
+    <url>http://maven.apache.org</url>
+
+    <properties>
+        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+    </properties>
+
+    <dependencies>
+        <dependency>
+            <groupId>junit</groupId>
+            <artifactId>junit</artifactId>
+            <version>3.8.1</version>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-web</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.projectlombok</groupId>
+            <artifactId>lombok</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>io.minio</groupId>
+            <artifactId>minio</artifactId>
+            <version>7.1.0</version>
+        </dependency>
+    </dependencies>
+</project>

+ 22 - 0
src/main/java/com/zksy/MinioConfiguration.java

@@ -0,0 +1,22 @@
+package com.zksy;
+
+import com.zksy.service.IpCounterService;
+import com.zksy.service.MinioFileStorageService;
+import com.zksy.service.impl.IpCounterServiceImpl;
+import com.zksy.service.impl.MinioFileStorageServiceImpl;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+
+@Configuration
+public class MinioConfiguration {
+    @Bean
+    public IpCounterService ipCounterService(){
+        return new IpCounterServiceImpl();
+    }
+
+    @Bean
+    public MinioFileStorageService minioFileStorageService(){
+        return new MinioFileStorageServiceImpl();
+    }
+
+}

+ 30 - 0
src/main/java/com/zksy/config/MinIOConfig.java

@@ -0,0 +1,30 @@
+package com.zksy.config;
+
+import com.zksy.service.MinioFileStorageService;
+import io.minio.MinioClient;
+import lombok.Data;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
+import org.springframework.boot.context.properties.EnableConfigurationProperties;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+
+
+@Data
+@Configuration
+@EnableConfigurationProperties({MinIOConfigProperties.class})
+@ConditionalOnClass(MinioFileStorageService.class)
+public class MinIOConfig {
+
+    @Autowired
+    private MinIOConfigProperties minIOConfigProperties;
+
+    @Bean
+    public MinioClient buildMinioClient() {
+        return MinioClient
+                .builder()
+                .credentials(minIOConfigProperties.getAccessKey(), minIOConfigProperties.getSecretKey())
+                .endpoint(minIOConfigProperties.getEndpoint())
+                .build();
+    }
+}

+ 18 - 0
src/main/java/com/zksy/config/MinIOConfigProperties.java

@@ -0,0 +1,18 @@
+package com.zksy.config;
+
+
+import lombok.Data;
+import org.springframework.boot.context.properties.ConfigurationProperties;
+
+import java.io.Serializable;
+
+@Data
+@ConfigurationProperties(prefix = "minio")  // 文件上传 配置前缀file.oss
+public class MinIOConfigProperties implements Serializable {
+
+    private String accessKey;
+    private String secretKey;
+    private String bucket;
+    private String endpoint;
+    private String readPath;
+}

+ 5 - 0
src/main/java/com/zksy/service/IpCounterService.java

@@ -0,0 +1,5 @@
+package com.zksy.service;
+
+public interface IpCounterService {
+    void record();
+}

+ 50 - 0
src/main/java/com/zksy/service/MinioFileStorageService.java

@@ -0,0 +1,50 @@
+package com.zksy.service;
+
+import io.minio.errors.*;
+import org.springframework.stereotype.Component;
+import org.springframework.web.multipart.MultipartFile;
+
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+import java.security.InvalidKeyException;
+import java.security.NoSuchAlgorithmException;
+import java.util.ArrayList;
+import java.util.List;
+
+
+public interface MinioFileStorageService {
+    /**
+     * 删除文件
+     * @param fileName 文件地址
+     */
+    public void deleteFile(String fileName);
+
+    /**
+     * 下载文件
+     * @param filePath 文件地址
+     * @param response 响应
+     */
+    public void downLoadFile(String filePath, HttpServletResponse response);
+
+    /**
+     * 上传文件
+     * @param file 文件
+     * @param businessType 业务类型
+     * @return
+     * @throws Exception
+     */
+    public String uploadFile(MultipartFile file, String businessType) throws Exception;
+    /**
+     * 批量上传文件
+     * @param files 文件列表
+     * @param businessType 业务类型
+     * @return
+     * @throws Exception
+     */
+    public List<String> uploadFileBatch(List<MultipartFile> files, String businessType) throws Exception;
+    /**
+     * 批量删除文件
+     * @param filePaths 文件地址list
+     */
+    public void deleteFileBatch(List<String> filePaths);
+}

+ 25 - 0
src/main/java/com/zksy/service/impl/IpCounterServiceImpl.java

@@ -0,0 +1,25 @@
+package com.zksy.service.impl;
+
+import com.zksy.service.IpCounterService;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
+
+import javax.servlet.http.HttpServletRequest;
+import java.util.HashMap;
+
+@Service
+public class IpCounterServiceImpl implements IpCounterService {
+
+    @Autowired
+    private HttpServletRequest request;
+
+    private final HashMap<String,Integer> ipCounter = new HashMap<>();
+    @Override
+    public void record() {
+        String ip = request.getRemoteAddr();
+        ipCounter.merge(ip, 1, Integer::sum);
+        ipCounter.forEach((k,v)->{
+            System.out.println(k+"访问了"+v+"次");
+        });
+    }
+}

+ 130 - 0
src/main/java/com/zksy/service/impl/MinioFileStorageServiceImpl.java

@@ -0,0 +1,130 @@
+package com.zksy.service.impl;
+
+import com.zksy.config.MinIOConfigProperties;
+import com.zksy.service.MinioFileStorageService;
+import io.minio.*;
+import io.minio.errors.*;
+import io.minio.messages.ObjectMetadata;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
+import org.springframework.util.StringUtils;
+import org.springframework.web.multipart.MultipartFile;
+
+import javax.annotation.PostConstruct;
+import javax.servlet.ServletOutputStream;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.nio.charset.StandardCharsets;
+import java.security.InvalidKeyException;
+import java.security.NoSuchAlgorithmException;
+import java.text.SimpleDateFormat;
+import java.util.*;
+
+@Service
+@Slf4j
+public class MinioFileStorageServiceImpl implements MinioFileStorageService {
+    @Autowired
+    private MinioClient minioClient;
+    @Autowired
+    private MinIOConfigProperties minIOConfigProperties;
+
+    @PostConstruct
+    public void init() {
+        try {
+            String bucketName = minIOConfigProperties.getBucket();
+            boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
+            if (!found) {
+                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
+                String policy = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":[\"*\"]},\"Action\":[\"s3:GetObject\"],\"Resource\":[\"arn:aws:s3:::"+bucketName+"/*\"]}]}";
+                minioClient.setBucketPolicy(SetBucketPolicyArgs.builder().bucket(bucketName).config(policy).build());
+            }
+            log.info("初始化MinIO成功");
+        } catch (Exception e) {
+            log.error("初始化MinIO失败", e);
+        }
+    }
+    @Override
+    public void deleteFile(String fileName) {
+        try {
+            minioClient.removeObject(RemoveObjectArgs.builder().bucket(minIOConfigProperties.getBucket()).object(fileName).build());
+        } catch (Exception e) {
+            log.error("删除文件失败", e);
+        }
+    }
+
+    @Override
+    public void downLoadFile(String filePath, HttpServletResponse response) {
+        try {
+            InputStream inputStream = minioClient.getObject(GetObjectArgs.builder()
+                    .bucket(minIOConfigProperties.getBucket())
+                    .object(filePath)
+                    .build()
+            );
+            response.setContentType("application/octet-stream");
+            response.setHeader("Content-Disposition", "attachment; filename=" + filePath);
+            OutputStream out = response.getOutputStream();
+            byte[] buffer = new byte[1024];
+            int length;
+            while ((length = inputStream.read(buffer)) > 0) {
+                out.write(buffer, 0, length);
+            }
+            out.flush();
+            out.close();
+        } catch (Exception e) {
+            log.error("下载文件失败", e);
+        }
+    }
+
+    /**
+     *
+     * @param file 文件
+     * @param businessType 业务类型
+     * @return filePath 文件的路径
+     */
+    @Override
+    public String uploadFile(MultipartFile file, String businessType) {
+        //获取文件后缀
+        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
+        //获取文件类型
+        String fileType = suffix.replace(".", "");
+        //获取主键id
+        Long uuid = UUID.randomUUID().getMostSignificantBits() & 0x7fffffffffffffffL;
+        String filePath = new SimpleDateFormat("yyyy/MM/dd").format(Calendar.getInstance().getTime());
+        filePath = "/" + filePath + "/" + businessType + "/" + fileType + "/" + uuid + suffix;
+        try {
+            minioClient.putObject(
+                    PutObjectArgs
+                            .builder()
+                            .bucket(minIOConfigProperties.getBucket())
+                            .object(filePath)
+                            .stream(file.getInputStream(), file.getSize(), ObjectWriteArgs.MIN_MULTIPART_SIZE)
+                            .build()
+            );
+        } catch (Exception e) {
+            log.error("上传文件失败", e);
+        }
+        return filePath;
+    }
+
+    @Override
+    public List<String> uploadFileBatch(List<MultipartFile> files, String businessType) {
+        List<String> resList = new ArrayList<>();
+        files.forEach(q->{
+            try {
+                String s = this.uploadFile(q, businessType);
+                resList.add(s);
+            }catch (Exception e){
+                log.error("上传文件失败", e);
+            }
+        });
+        return resList;
+    }
+
+    @Override
+    public void deleteFileBatch(List<String> filePaths) {
+        filePaths.forEach(this::deleteFile);
+    }
+}

+ 1 - 0
src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports

@@ -0,0 +1 @@
+com.zksy.MinioConfiguration

+ 38 - 0
src/test/java/com/zksy/MinioUtilApplicationTest.java

@@ -0,0 +1,38 @@
+package com.zksy;
+
+import junit.framework.Test;
+import junit.framework.TestCase;
+import junit.framework.TestSuite;
+
+/**
+ * Unit test for simple App.
+ */
+public class MinioUtilApplicationTest
+    extends TestCase
+{
+    /**
+     * Create the test case
+     *
+     * @param testName name of the test case
+     */
+    public MinioUtilApplicationTest(String testName )
+    {
+        super( testName );
+    }
+
+    /**
+     * @return the suite of tests being tested
+     */
+    public static Test suite()
+    {
+        return new TestSuite( MinioUtilApplicationTest.class );
+    }
+
+    /**
+     * Rigourous Test :-)
+     */
+    public void testApp()
+    {
+        assertTrue( true );
+    }
+}

+ 10 - 0
src/test/java/com/zksy/service/impl/MinioFileStorageServiceImplTest.java

@@ -0,0 +1,10 @@
+package com.zksy.service.impl;
+
+import junit.framework.TestCase;
+
+
+public class MinioFileStorageServiceImplTest extends TestCase {
+
+    public void testUploadFile() {
+    }
+}