Commit ef0f3e0f by changchao

minio服务

parent 12a7410d
HELP.md
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
!**/src/main/**/build/
!**/src/test/**/build/
### VS Code ###
.vscode/
/*
* Copyright 2007-present the original author or authors.
*
* Licensed 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
*
* https://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.
*/
import java.net.*;
import java.io.*;
import java.nio.channels.*;
import java.util.Properties;
public class MavenWrapperDownloader {
private static final String WRAPPER_VERSION = "0.5.6";
/**
* Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided.
*/
private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/"
+ WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar";
/**
* Path to the maven-wrapper.properties file, which might contain a downloadUrl property to
* use instead of the default one.
*/
private static final String MAVEN_WRAPPER_PROPERTIES_PATH =
".mvn/wrapper/maven-wrapper.properties";
/**
* Path where the maven-wrapper.jar will be saved to.
*/
private static final String MAVEN_WRAPPER_JAR_PATH =
".mvn/wrapper/maven-wrapper.jar";
/**
* Name of the property which should be used to override the default download url for the wrapper.
*/
private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl";
public static void main(String args[]) {
System.out.println("- Downloader started");
File baseDirectory = new File(args[0]);
System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath());
// If the maven-wrapper.properties exists, read it and check if it contains a custom
// wrapperUrl parameter.
File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH);
String url = DEFAULT_DOWNLOAD_URL;
if (mavenWrapperPropertyFile.exists()) {
FileInputStream mavenWrapperPropertyFileInputStream = null;
try {
mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile);
Properties mavenWrapperProperties = new Properties();
mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream);
url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url);
} catch (IOException e) {
System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'");
} finally {
try {
if (mavenWrapperPropertyFileInputStream != null) {
mavenWrapperPropertyFileInputStream.close();
}
} catch (IOException e) {
// Ignore ...
}
}
}
System.out.println("- Downloading from: " + url);
File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH);
if (!outputFile.getParentFile().exists()) {
if (!outputFile.getParentFile().mkdirs()) {
System.out.println(
"- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'");
}
}
System.out.println("- Downloading to: " + outputFile.getAbsolutePath());
try {
downloadFileFromURL(url, outputFile);
System.out.println("Done");
System.exit(0);
} catch (Throwable e) {
System.out.println("- Error downloading");
e.printStackTrace();
System.exit(1);
}
}
private static void downloadFileFromURL(String urlString, File destination) throws Exception {
if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) {
String username = System.getenv("MVNW_USERNAME");
char[] password = System.getenv("MVNW_PASSWORD").toCharArray();
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
}
URL website = new URL(urlString);
ReadableByteChannel rbc;
rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(destination);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
rbc.close();
}
}
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.3/apache-maven-3.6.3-bin.zip
wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar
This diff is collapsed. Click to expand it.
@REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements. See the NOTICE file
@REM distributed with this work for additional information
@REM regarding copyright ownership. The ASF licenses this file
@REM to you under the Apache License, Version 2.0 (the
@REM "License"); you may not use this file except in compliance
@REM with the License. You may obtain a copy of the License at
@REM
@REM https://www.apache.org/licenses/LICENSE-2.0
@REM
@REM Unless required by applicable law or agreed to in writing,
@REM software distributed under the License is distributed on an
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@REM KIND, either express or implied. See the License for the
@REM specific language governing permissions and limitations
@REM under the License.
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Maven Start Up Batch script
@REM
@REM Required ENV vars:
@REM JAVA_HOME - location of a JDK home dir
@REM
@REM Optional ENV vars
@REM M2_HOME - location of maven2's installed home dir
@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending
@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
@REM e.g. to debug Maven itself, use
@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
@REM ----------------------------------------------------------------------------
@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
@echo off
@REM set title of command window
title %0
@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on'
@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
@REM set %HOME% to equivalent of $HOME
if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
@REM Execute a user defined script before this one
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
@REM check for pre script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat"
if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd"
:skipRcPre
@setlocal
set ERROR_CODE=0
@REM To isolate internal variables from possible post scripts, we use another setlocal
@setlocal
@REM ==== START VALIDATION ====
if not "%JAVA_HOME%" == "" goto OkJHome
echo.
echo Error: JAVA_HOME not found in your environment. >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
:OkJHome
if exist "%JAVA_HOME%\bin\java.exe" goto init
echo.
echo Error: JAVA_HOME is set to an invalid directory. >&2
echo JAVA_HOME = "%JAVA_HOME%" >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
@REM ==== END VALIDATION ====
:init
@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
@REM Fallback to current working directory if not found.
set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
set EXEC_DIR=%CD%
set WDIR=%EXEC_DIR%
:findBaseDir
IF EXIST "%WDIR%"\.mvn goto baseDirFound
cd ..
IF "%WDIR%"=="%CD%" goto baseDirNotFound
set WDIR=%CD%
goto findBaseDir
:baseDirFound
set MAVEN_PROJECTBASEDIR=%WDIR%
cd "%EXEC_DIR%"
goto endDetectBaseDir
:baseDirNotFound
set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
cd "%EXEC_DIR%"
:endDetectBaseDir
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
@setlocal EnableExtensions EnableDelayedExpansion
for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
:endReadAdditionalConfig
SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO (
IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B
)
@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
@REM This allows using the maven wrapper in projects that prohibit checking in binary data.
if exist %WRAPPER_JAR% (
if "%MVNW_VERBOSE%" == "true" (
echo Found %WRAPPER_JAR%
)
) else (
if not "%MVNW_REPOURL%" == "" (
SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
)
if "%MVNW_VERBOSE%" == "true" (
echo Couldn't find %WRAPPER_JAR%, downloading it ...
echo Downloading from: %DOWNLOAD_URL%
)
powershell -Command "&{"^
"$webclient = new-object System.Net.WebClient;"^
"if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^
"$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^
"}"^
"[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^
"}"
if "%MVNW_VERBOSE%" == "true" (
echo Finished downloading %WRAPPER_JAR%
)
)
@REM End of extension
@REM Provide a "standardized" way to retrieve the CLI args that will
@REM work with both Windows and non-Windows executions.
set MAVEN_CMD_LINE_ARGS=%*
%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
if ERRORLEVEL 1 goto error
goto end
:error
set ERROR_CODE=1
:end
@endlocal & set ERROR_CODE=%ERROR_CODE%
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost
@REM check for post script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat"
if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd"
:skipRcPost
@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
if "%MAVEN_BATCH_PAUSE%" == "on" pause
if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%
exit /B %ERROR_CODE%
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.4</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.founder</groupId>
<artifactId>minio</artifactId>
<version>1.0-SNAPSHOT</version>
<name>minio</name>
<description>分布式文件系统</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>io.minio</groupId>
<artifactId>minio</artifactId>
<version>8.1.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>2.0.4</version>
<exclusions>
<exclusion>
<artifactId>guava</artifactId>
<groupId>com.google.guava</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.74</version>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.5.7</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.46</version>
<scope>runtime</scope>
</dependency>
<!-- druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.4</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.1</version>
</dependency>
</dependencies>
<build>
<finalName>minio</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>3.1.0</version>
</plugin>
</plugins>
</build>
</project>
package com.founder.minio.bean;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import lombok.Data;
@TableName(value = "t_file")
@Data
public class File extends Model<File> {
@TableId(value = "id")
private String id;
private String fileId;
private String fileName;
private String fileType;
private Long fileSize;
private String fileUrl;
private String serviceId;
private String serviceType;
private int isUse;
private int isDelete;
private String fileBucketName;
}
package com.founder.minio.config;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import com.alibaba.druid.support.spring.stat.DruidStatInterceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.support.DefaultPointcutAdvisor;
import org.springframework.aop.support.JdkRegexpMethodPointcut;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import javax.sql.DataSource;
import java.sql.SQLException;
/**
* @Author 高新启蒙Array老师
*/
@Configuration
public class DruidConfiguration {
private static final Logger logger = LoggerFactory.getLogger(DruidConfiguration.class);
private static final String DB_PREFIX = "spring.datasource";
@Bean
public ServletRegistrationBean druidServlet() {
logger.info("init Druid Servlet Configuration ");
ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
// IP白名单
servletRegistrationBean.addInitParameter("allow", "");
// IP黑名单(共同存在时,deny优先于allow)
servletRegistrationBean.addInitParameter("deny", "192.168.1.100");
//控制台管理用户
servletRegistrationBean.addInitParameter("loginUsername", "admin");
servletRegistrationBean.addInitParameter("loginPassword", "admin");
//是否能够重置数据 禁用HTML页面上的“Reset All”功能
servletRegistrationBean.addInitParameter("resetEnable", "false");
return servletRegistrationBean;
}
@Bean
public FilterRegistrationBean filterRegistrationBean() {
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());
filterRegistrationBean.addUrlPatterns("/*");
filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
return filterRegistrationBean;
}
//解决 spring.datasource.filters=stat,wall,log4j 无法正常注册进去
@Component
@ConfigurationProperties(prefix = DB_PREFIX)
class IDataSourceProperties {
private String url;
private String username;
private String password;
private String driverClassName;
private int initialSize;
private int minIdle;
private int maxActive;
private int maxWait;
private int timeBetweenEvictionRunsMillis;
private int minEvictableIdleTimeMillis;
private String validationQuery;
private boolean testWhileIdle;
private boolean testOnBorrow;
private boolean testOnReturn;
private boolean poolPreparedStatements;
private int maxPoolPreparedStatementPerConnectionSize;
private String filters;
private String connectionProperties;
@Bean //声明其为Bean实例
@Primary //在同样的DataSource中,首先使用被标注的DataSource
public DataSource dataSource() {
DruidDataSource datasource = new DruidDataSource();
datasource.setUrl(url);
datasource.setUsername(username);
datasource.setPassword(password);
datasource.setDriverClassName(driverClassName);
//configuration
datasource.setInitialSize(initialSize);
datasource.setMinIdle(minIdle);
datasource.setMaxActive(maxActive);
datasource.setMaxWait(maxWait);
datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
datasource.setValidationQuery(validationQuery);
datasource.setTestWhileIdle(testWhileIdle);
datasource.setTestOnBorrow(testOnBorrow);
datasource.setTestOnReturn(testOnReturn);
datasource.setPoolPreparedStatements(poolPreparedStatements);
datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
try {
datasource.setFilters(filters);
} catch (SQLException e) {
System.err.println("druid configuration initialization filter: " + e);
}
datasource.setConnectionProperties(connectionProperties);
return datasource;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getDriverClassName() {
return driverClassName;
}
public void setDriverClassName(String driverClassName) {
this.driverClassName = driverClassName;
}
public int getInitialSize() {
return initialSize;
}
public void setInitialSize(int initialSize) {
this.initialSize = initialSize;
}
public int getMinIdle() {
return minIdle;
}
public void setMinIdle(int minIdle) {
this.minIdle = minIdle;
}
public int getMaxActive() {
return maxActive;
}
public void setMaxActive(int maxActive) {
this.maxActive = maxActive;
}
public int getMaxWait() {
return maxWait;
}
public void setMaxWait(int maxWait) {
this.maxWait = maxWait;
}
public int getTimeBetweenEvictionRunsMillis() {
return timeBetweenEvictionRunsMillis;
}
public void setTimeBetweenEvictionRunsMillis(int timeBetweenEvictionRunsMillis) {
this.timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis;
}
public int getMinEvictableIdleTimeMillis() {
return minEvictableIdleTimeMillis;
}
public void setMinEvictableIdleTimeMillis(int minEvictableIdleTimeMillis) {
this.minEvictableIdleTimeMillis = minEvictableIdleTimeMillis;
}
public String getValidationQuery() {
return validationQuery;
}
public void setValidationQuery(String validationQuery) {
this.validationQuery = validationQuery;
}
public boolean isTestWhileIdle() {
return testWhileIdle;
}
public void setTestWhileIdle(boolean testWhileIdle) {
this.testWhileIdle = testWhileIdle;
}
public boolean isTestOnBorrow() {
return testOnBorrow;
}
public void setTestOnBorrow(boolean testOnBorrow) {
this.testOnBorrow = testOnBorrow;
}
public boolean isTestOnReturn() {
return testOnReturn;
}
public void setTestOnReturn(boolean testOnReturn) {
this.testOnReturn = testOnReturn;
}
public boolean isPoolPreparedStatements() {
return poolPreparedStatements;
}
public void setPoolPreparedStatements(boolean poolPreparedStatements) {
this.poolPreparedStatements = poolPreparedStatements;
}
public int getMaxPoolPreparedStatementPerConnectionSize() {
return maxPoolPreparedStatementPerConnectionSize;
}
public void setMaxPoolPreparedStatementPerConnectionSize(int maxPoolPreparedStatementPerConnectionSize) {
this.maxPoolPreparedStatementPerConnectionSize = maxPoolPreparedStatementPerConnectionSize;
}
public String getFilters() {
return filters;
}
public void setFilters(String filters) {
this.filters = filters;
}
public String getConnectionProperties() {
return connectionProperties;
}
public void setConnectionProperties(String connectionProperties) {
this.connectionProperties = connectionProperties;
}
}
@Bean
public DruidStatInterceptor druidStatInterceptor() {
DruidStatInterceptor dsInterceptor = new DruidStatInterceptor();
return dsInterceptor;
}
@Bean
@Scope("prototype")
public JdkRegexpMethodPointcut druidStatPointcut() {
JdkRegexpMethodPointcut pointcut = new JdkRegexpMethodPointcut();
pointcut.setPattern("com.founder.controller.*");
pointcut.setPattern("com.founder.mapper.*");
return pointcut;
}
@Bean
public DefaultPointcutAdvisor druidStatAdvisor(DruidStatInterceptor druidStatInterceptor, JdkRegexpMethodPointcut druidStatPointcut) {
DefaultPointcutAdvisor defaultPointAdvisor = new DefaultPointcutAdvisor();
defaultPointAdvisor.setPointcut(druidStatPointcut);
defaultPointAdvisor.setAdvice(druidStatInterceptor);
return defaultPointAdvisor;
}
}
package com.founder.minio.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import java.util.Collections;
@Configuration
public class GlobalCorsConfig {
@Bean
public CorsFilter corsFilter() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
//1,允许任何来源
corsConfiguration.setAllowedOriginPatterns(Collections.singletonList("*"));
//2,允许任何请求头
corsConfiguration.addAllowedHeader(CorsConfiguration.ALL);
//3,允许任何方法
corsConfiguration.addAllowedMethod(CorsConfiguration.ALL);
//4,允许凭证
corsConfiguration.setAllowCredentials(true);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", corsConfiguration);
return new CorsFilter(source);
}
}
package com.founder.minio.config;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import java.util.Date;
/**
* @version:1.0
* @author: Array老师
*/
@Component
public class MetaObjectHandlerConfig implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
System.out.println("插入方法实体填充");
setFieldValByName("testDate", new Date(), metaObject);
}
@Override
public void updateFill(MetaObject metaObject) {
System.out.println("更新方法实体填充");
}
}
package com.founder.minio.config;
import io.minio.MinioClient;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
@Data
@Configuration
public class MinIoClientConfig {
@Value("${minio.endpoint}")
private String endpoint;
@Value("${minio.accessKey}")
private String accessKey;
@Value("${minio.secretKey}")
private String secretKey;
@Value("${minio.port}")
private int port;
@Value("${minio.bucketName}")
private String bucketName;
@Value("${minio.minioHttps}")
private Boolean minioHttps;
/**
* 注入minio 客户端
* @return
*/
@Bean
public MinioClient minioClient(){
MinioClient client = MinioClient.builder()
.endpoint(endpoint, port, minioHttps)
.credentials(accessKey, secretKey)
.build();
try {
client.ignoreCertCheck();
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return client;
}
}
package com.founder.minio.config;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@EnableTransactionManagement
@Configuration
@MapperScan("com.founder.minio.mapper")
public class MybatisPlusConfig {
/**
* mybatis-plus分页插件
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
// paginationInterceptor.setLimit(你的最大单页限制数量,默认 500 条,小于 0 如 -1 不受限制);
return new PaginationInterceptor();
}
}
package com.founder.minio.config;
import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
* @Description Swagger文档
* @Author Array老师
* @Date
**/
@Configuration
@EnableSwagger2
@EnableKnife4j
public class SwaggerConfiguration {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.founder"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("founder接口管理文档")
.description("founder:接口管理文档")
.termsOfServiceUrl("http://127.0.0.1:xxxx/")
.contact(new Contact("chent","","chentian@founder.com"))
.version("1.0")
.build();
}
}
package com.founder.minio.controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.founder.minio.bean.File;
import com.founder.minio.service.FileService;
import com.founder.minio.service.MinioSerivce;
import com.founder.minio.util.CloudResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.Map;
/**
* Mysql端存储的文件属性信息和minio文件服务器文件进行关联
*
*/
@RestController
@Api(value = "FileController",tags = {"文件属性值操作"})
@RequestMapping("rest/file")
public class FileController {
@Resource
private FileService fileService;
@Resource
private MinioSerivce minioSerivce;
/**
* minio服务器所有文件的属性列表
* current size name
*/
@PostMapping("/page")
@ApiOperation(value = "文件属性分页",httpMethod = "POST",produces = "分页")
public CloudResult page(@RequestBody Map<String,Object> obj) {
if(null!=obj&&obj.size()>0) {
int current = (int) obj.get("current");
int size = (int) obj.get("size");
String name = (String) obj.get("name");
IPage<File> iPage = new Page<>(current, size);
IPage<File> fileIPage;
if(null==name) {
fileIPage = fileService.page(iPage);
} else {
// 模糊查询
fileIPage = fileService.page(iPage,new QueryWrapper<File>().lambda().like(File::getFileName,name));
}
return CloudResult.createBySuccess("成功",fileIPage);
}
return CloudResult.createByError();
}
/**
* 添加
*/
@PostMapping("/save")
@ApiOperation(value = "文件属性的添加",httpMethod = "POST",produces = "添加")
public CloudResult save(@RequestBody File file) {
if(null!=file&&!("").equals(file)){
boolean b = fileService.save(file);
return CloudResult.createBySuccess("添加成功!",b);
}
return CloudResult.createByError();
}
/**
* 添加
*/
@PostMapping("/update")
@ApiOperation(value = "文件属性的更新",httpMethod = "POST",produces = "更新")
public CloudResult update(@RequestBody File file) {
if(null!=file&&!("").equals(file)){
boolean b = fileService.updateById(file);
return CloudResult.createBySuccess("更新成功!",b);
}
return CloudResult.createByError();
}
/**
* 删除
*/
@PostMapping("/delete")
@ApiOperation(value = "文件属性的删除",httpMethod = "POST",produces = "删除")
public CloudResult delete(@RequestBody File file) {
if(null!=file&&!("").equals(file)){
//1。从minio服务器上删除
minioSerivce.delete(file);
//2. 从mysql数据库中删除该文件对应的属性
boolean b = fileService.removeById(file);
return CloudResult.createBySuccess("删除成功!",b);
}
return CloudResult.createByError();
}
}
package com.founder.minio.controller;
import com.founder.minio.bean.File;
import com.founder.minio.service.MinioSerivce;
import com.founder.minio.util.CloudResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
/**
* 真实操作minio服务器的非结构化文件,调用minio的官方API,minio8.x
* 各个版本的api略有不同
*/
@RequestMapping("rest/minio")
@Api(value = "文件服务器接口")
@CrossOrigin
@RestController
public class MinioController {
@Resource
private MinioSerivce minioSerivce;
/**
* 上传
*/
@RequestMapping("/upload")
@ApiOperation(value = "上传",httpMethod = "POST",produces = "文件服务器上传")
public CloudResult upload(MultipartFile file){
CloudResult cloudResult = minioSerivce.upload(file);
return cloudResult;
}
/**
* 下载
*/
@RequestMapping("/download")
@ApiOperation(value = "下载",httpMethod = "POST",produces = "文件服务器下载")
public void download(String fileName, HttpServletResponse response){
minioSerivce.download(fileName,response);
}
/**
* 删除
*/
@RequestMapping("/delete")
@ApiOperation(value = "删除",httpMethod = "POST",produces = "文件服务器删除")
public CloudResult delete(@RequestBody File file){
CloudResult cloudResult = minioSerivce.delete(file);
return cloudResult;
}
/**
* 分享,外链
*/
@RequestMapping("/share")
@ApiOperation(value = "分享",httpMethod = "POST",produces = "文件服务器分享")
public CloudResult share(@RequestBody File file){
CloudResult cloudResult = minioSerivce.share(file);
return cloudResult;
}
}
package com.founder.minio;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class founderMinioApplication {
public static void main(String[] args) {
SpringApplication.run(founderMinioApplication.class, args);
}
}
package com.founder.minio.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.founder.minio.bean.File;
public interface FileMapper extends BaseMapper<File> {
}
package com.founder.minio.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.founder.minio.bean.File;
public interface FileService extends IService<File> {
}
package com.founder.minio.service;
import com.founder.minio.bean.File;
import com.founder.minio.util.CloudResult;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
public interface MinioSerivce {
CloudResult upload(MultipartFile file);
void download(String fileName, HttpServletResponse response);
CloudResult delete(File file);
CloudResult share(File file);
}
package com.founder.minio.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.founder.minio.bean.File;
import com.founder.minio.mapper.FileMapper;
import com.founder.minio.service.FileService;
import org.springframework.stereotype.Service;
@Service
public class FileServiceImpl extends ServiceImpl<FileMapper, File> implements FileService {
}
package com.founder.minio.service.impl;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.founder.minio.bean.File;
import com.founder.minio.util.CloudResult;
import com.founder.minio.util.MinIoUtil;
import com.founder.minio.config.MinIoClientConfig;
import com.founder.minio.service.FileService;
import com.founder.minio.service.MinioSerivce;
import io.minio.GetPresignedObjectUrlArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.*;
import io.minio.http.Method;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
@Service
public class MinioServiceImpl implements MinioSerivce {
@Resource
private MinioClient minioClient;
@Resource
private MinIoUtil minIoUtil;
@Resource
private MinIoClientConfig minIoClientConfig;
@Resource
private FileService fileService;
@Override
public CloudResult upload(MultipartFile file) {
//获取原始文件名称
String fileName = file.getOriginalFilename();
Long fileSize = file.getSize();
//按照年月日的方式进行存储,同时文件的id为uuid生成或者idworker
String objName = new SimpleDateFormat("yyyy/MM/dd").format(new Date())+ IdWorker.getId()
+fileName.substring(fileName.lastIndexOf("."));
// 1.上传文件
try {
PutObjectArgs objectArgs = PutObjectArgs.builder().object(objName)
.bucket(minIoClientConfig.getBucketName())
.contentType(file.getContentType())
.stream(file.getInputStream(), fileSize, -1).build();
minioClient.putObject(objectArgs);
} catch (Exception e) {
e.printStackTrace();
}
//2.上传后生成能够浏览器访问的url或者称分享的url
try {
String objectUrl = minioClient.getPresignedObjectUrl(new GetPresignedObjectUrlArgs().builder()
.bucket(minIoClientConfig.getBucketName()).object(objName).method(Method.GET).build());
// 3.文件属性入Mysql的数据库存档
File file1 = new File();
file1.setFileName(fileName);
file1.setFileSize(fileSize/1024);
file1.setFileBucketName(minIoClientConfig.getBucketName());
file1.setFileUrl(objName);
file1.setFileType(fileName.substring(fileName.lastIndexOf(".")));
file1.setIsUse(0);
file1.setIsDelete(0);
boolean b = fileService.save(file1);
if(b) {
return CloudResult.createBySuccess("上传成功!",b);
} else {
return CloudResult.createByError();
}
} catch (ErrorResponseException e) {
e.printStackTrace();
} catch (InsufficientDataException e) {
e.printStackTrace();
} catch (InternalException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (InvalidResponseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (XmlParserException e) {
e.printStackTrace();
} catch (ServerException e) {
e.printStackTrace();
}
return CloudResult.createByError();
}
@Override
public void download(String fileName, HttpServletResponse response) {
minIoUtil.downloadObject(minIoClientConfig.getBucketName(),fileName,response);
}
@Override
public CloudResult delete(File file) {
boolean b = minIoUtil.removeObject(minIoClientConfig.getBucketName(), file.getFileUrl());
if(b) {
return CloudResult.createBySuccess("删除成功!",b);
} else {
return CloudResult.createByError();
}
}
@Override
public CloudResult share(File file) {
try {
String objectUrl = minioClient.getPresignedObjectUrl(new GetPresignedObjectUrlArgs().builder()
.bucket(minIoClientConfig.getBucketName()).object(file.getFileUrl()).method(Method.GET).build());
return CloudResult.createBySuccess("创建分享链接成功",objectUrl);
} catch (ErrorResponseException e) {
e.printStackTrace();
} catch (InsufficientDataException e) {
e.printStackTrace();
} catch (InternalException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (InvalidResponseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (XmlParserException e) {
e.printStackTrace();
} catch (ServerException e) {
e.printStackTrace();
}
return CloudResult.createByError();
}
}
package com.founder.minio.util;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.annotation.JsonIgnore;
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.Enumeration;
/**
* @description: 通用服务响应对象
**/
//保证序列化json的时候,如果是null的对象,key也会消失
public class CloudResult<T> implements Serializable {
//1.定义属性
private int status;
private String msg;
private T data;
//2.定义构造函数
private CloudResult(int status) {
this.status = status;
}
private CloudResult(int status, T data) {
this.status = status;
this.data = data;
}
private CloudResult(int status, String msg, T data) {
this.status = status;
this.msg = msg;
this.data = data;
}
private CloudResult(int status, String msg) {
this.status = status;
this.msg = msg;
}
//3.getter方法
public int getStatus() {
return status;
}
public T getData() {
return data;
}
public String getMsg() {
return msg;
}
@JsonIgnore
//使之不在json序列化结果当中
//4.判断这个响应是不是一个正确的响应
public boolean isSuccess() {
return this.status == ResponseCode.SUCCESS.getCode();
}
//5.定义返回对象的方法
public static <T> CloudResult<T> createBySuccess() {
return new CloudResult<T>(ResponseCode.SUCCESS.getCode());
}
public static <T> CloudResult<T> createBySuccessMessage(String msg) {
return new CloudResult<T>(ResponseCode.SUCCESS.getCode(), msg);
}
public static <T> CloudResult<T> createBySuccess(T data) {
return new CloudResult<T>(ResponseCode.SUCCESS.getCode(), data);
}
public static <T> CloudResult<T> createByCodeSuccess(int status, String msg, T data) {
return new CloudResult<T>(status,msg, data);
}
public static <T> CloudResult<T> createBySuccess(String msg, T data) {
return new CloudResult<T>(ResponseCode.SUCCESS.getCode(), msg, data);
}
public static <T> CloudResult<T> createByError() {
return new CloudResult<T>(ResponseCode.ERROR.getCode(), ResponseCode.ERROR.getDesc());
}
public static <T> CloudResult<T> createByErrorMessage(String errorMessage) {
return new CloudResult<T>(ResponseCode.ERROR.getCode(), errorMessage);
}
public static <T> CloudResult<T> createByErrorCodeMessage(int errorCode, String errorMessage) {
return new CloudResult<T>(errorCode, errorMessage);
}/**
* 将request参数值转为json
*/
public static JSONObject request2Json(HttpServletRequest request) {
JSONObject requestJson = new JSONObject();
Enumeration paramNames = request.getParameterNames();
while (paramNames.hasMoreElements()) {
String paramName = (String) paramNames.nextElement();
String[] pv = request.getParameterValues(paramName);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < pv.length; i++) {
if (pv[i].length() > 0) {
if (i > 0) {
sb.append(",");
}
sb.append(pv[i]);
}
}
requestJson.put(paramName, sb.toString());
}
return requestJson;
}
/**
* 将request转JSON
* 并且验证非空字段
*/
public static JSONObject convert2JsonAndCheckRequiredColumns(HttpServletRequest request, String requiredColumns) {
JSONObject jsonObject = request2Json(request);
hasAllRequired(jsonObject, requiredColumns);
return jsonObject;
}
/**
* 验证是否含必填字段
*
* @param requiredColumns 必填的参数字段名称 逗号隔开 比如"userId,name,telephone"
*/
public static void hasAllRequired(final JSONObject jsonObject, String requiredColumns) {
if (!isNullOrEmpty(requiredColumns)) {
//验证字段非空
String[] columns = requiredColumns.split(",");
String missCol = "";
for (String column : columns) {
Object val = jsonObject.get(column.trim());
if (isNullOrEmpty(val)) {
missCol += column + " ";
}
}
if (!isNullOrEmpty(missCol)) {
jsonObject.clear();
jsonObject.put("code", "CodeEnum.ERROR_400");
jsonObject.put("msg", "缺少必填参数:" + missCol.trim());
jsonObject.put("info", new JSONObject());
}
}
}
public static boolean isNullOrEmpty(String str) {
return null == str || "".equals(str) || "null".equals(str);
}
public static boolean isNullOrEmpty(Object obj) {
return null == obj || "".equals(obj);
}
}
package com.founder.minio.util;
import io.minio.*;
import io.minio.messages.Bucket;
import io.minio.messages.Item;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
import io.minio.http.Method;
import io.minio.messages.*;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.LinkedList;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import static io.minio.GetPresignedObjectUrlArgs.DEFAULT_EXPIRY_TIME;
/**
* minio8的操作工具类,通用版
*/
@Component
public class MinIoUtil {
@Autowired
private MinioClient minioClient;
/**
* 判断存储桶,存在返回true
* @param bucketName 存储桶名称
* @return
*/
@SneakyThrows
public boolean bucketExists(String bucketName) {
boolean flag = false;
flag = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
if (flag) {
return true;
}
return false;
}
/**
* 创建
*/
@SneakyThrows
public boolean makeBucket(String bucketName) {
boolean flag = bucketExists(bucketName);
if (flag) {
return false;
} else {
minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
return true;
}
}
/**
* 删除
* @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(RemoveBucketArgs.builder().bucket(bucketName).build());
flag = bucketExists(bucketName);
if (!flag) {
return true;
}
}
return false;
}
/**
* 查询列表
* @return
*/
@SneakyThrows
public List<String> listBucketNames() {
List<Bucket> bucketList = listBuckets();
List<String> bucketListName = new ArrayList<>(bucketList.size());
for (Bucket bucket : bucketList) {
bucketListName.add(bucket.name());
}
return bucketListName;
}
/**
* 查询所有
* @return
*/
@SneakyThrows
public List<Bucket> listBuckets() {
return minioClient.listBuckets();
}
/**
* 查询存储中的对象
*/
@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;
}
/**
* 查询所有对象
*/
@SneakyThrows
public Iterable<Result<Item>> listObjects(String bucketName) {
return minioClient.listObjects(ListObjectsArgs.builder().bucket(bucketName).build());
}
/**
* 通过prefix查询
* @param bucketName 存储桶名称
* @param prefix 前缀
* @param after 后缀
* @param maxKeys 最大数量
* @return
*/
@SneakyThrows
public Iterable<Result<Item>> listObjects(String bucketName, String prefix, String after, int maxKeys) {
ListObjectsArgs.Builder builder = ListObjectsArgs.builder().bucket(bucketName);
if (prefix != null && prefix.length() > 0) {
builder.prefix(prefix);
}
if (after != null && after.length() > 0) {
builder.startAfter(after);
}
if (maxKeys > 0) {
builder.maxKeys(maxKeys);
}
return minioClient.listObjects(builder.build());
}
/**
* 删除
*/
@SneakyThrows
public void deleteObjectTags(String bucketName, String objectName) {
minioClient.deleteObjectTags(DeleteObjectTagsArgs.builder().bucket(bucketName).object(objectName).build());
}
/**
* 有时候是IO流的形式进行读取或者传递接口
* @return
*/
@SneakyThrows
public InputStream getObject(String bucketName, String objectName) {
InputStream stream = minioClient.getObject(
GetObjectArgs.builder()
.bucket(bucketName)
.object(objectName)
.build());
return stream;
}
/**
* 通过起始位置进行控制续传
* @param bucketName 存储桶名称
* @param objectName 存储桶里的对象名称
* @param offset 起始字节的位置
* @param length 要读取的长度 (可选,如果无值则代表读到文件结尾)
* @return
*/
@SneakyThrows
public InputStream getObject(String bucketName, String objectName, long offset, Long length) {
InputStream stream = minioClient.getObject(
GetObjectArgs.builder()
.bucket(bucketName)
.object(objectName)
.offset(offset)
.length(length)
.build());
return stream;
}
/**
* 查询对应对象的标签
* @return
*/
public Tags getObjectTags(String bucketName, String objectName) {
Tags tags = null;
try {
tags = minioClient.getObjectTags(GetObjectTagsArgs.builder().bucket(bucketName).object(objectName).build());
} catch (Exception e) {
//e.printStackTrace();
throw new RuntimeException(e.getMessage());
}
return tags;
}
/**
* 删除
*/
@SneakyThrows
public boolean removeObject(String bucketName, String objectName) {
minioClient.removeObject(RemoveObjectArgs.builder().bucket(bucketName).object(objectName).build());
return true;
}
/**
* 批量删除
*/
@SneakyThrows
public List<String> removeObjects(String bucketName, List<String> objectNames) {
List<String> deleteErrorNames = new ArrayList<>();
boolean flag = bucketExists(bucketName);
if (flag) {
List<DeleteObject> list = new LinkedList<>();
objectNames.forEach(item -> list.add(new DeleteObject(item)));
Iterable<Result<DeleteError>> results = minioClient.removeObjects(RemoveObjectsArgs.builder().bucket(bucketName).objects(list).build());
for (Result<DeleteError> result : results) {
DeleteError error = result.get();
deleteErrorNames.add(error.objectName());
}
}
return deleteErrorNames;
}
/**
* 给文件添加tags
*/
@SneakyThrows
public void setObjectTags(String bucketName, String objectName, Map<String, String> tags) {
minioClient.setObjectTags(SetObjectTagsArgs.builder().bucket(bucketName).object(objectName).tags(tags).build());
}
/**
* 分享链接
* @param bucketName 存储桶名称
* @param objectName 存储桶里的对象名称
* @param expires 失效时间(以秒为单位),默认是7天,不得大于七天
* @return
*/
@SneakyThrows
public String getPresignedObjectUrl(String bucketName, String objectName, Integer expires, Method method) {
String url = "";
if (expires < 1 || expires > DEFAULT_EXPIRY_TIME) {
throw new Exception();
}
if (method == null) {
method = Method.GET;
}
url = minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder()
.method(method)
.bucket(bucketName).object(objectName)
.expiry(expires, TimeUnit.SECONDS).build());
return url;
}
/**
* 下载文件方式1
*/
@SneakyThrows
public void downloadObject(String bucketName, String objectName, String fileName) {
minioClient.downloadObject(
DownloadObjectArgs.builder()
.bucket(bucketName)
.object(objectName)
.filename(fileName)
.build());
}
/**
* 下载文件方式2
*/
public void downloadObject(String bucketName, String objectName, HttpServletResponse response) {
try {
InputStream is = getObject(bucketName, objectName);
if(is == null){
return;
}
String fileName = objectName.substring(objectName.indexOf("/")+1 , objectName.length());
response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
ServletOutputStream servletOutputStream = response.getOutputStream();
int len;
byte[] buffer = new byte[1024];
while ((len = is.read(buffer)) > 0) {
servletOutputStream.write(buffer, 0, len);
}
servletOutputStream.flush();
is.close();
servletOutputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
package com.founder.minio.util;
public enum ResponseCode {
//1.定义枚举值
ERROR(0,"ERROR"),
SUCCESS(1,"SUCCESS"),
NEED_LOGIN(10,"NEED_LOGIN"),
ILLEGAL_ARGUMENT(2,"ILLEGAL_ARGUMENT");
//2.定义枚举属性
private final int code;
private final String desc;
//3.定义构造函数
ResponseCode(int code, String desc){
this.code = code;
this.desc = desc;
}
//4.定义get方法
public int getCode(){
return code;
}
public String getDesc(){
return desc;
}
}
server:
port: 3003
spring:
datasource:
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
driverClassName: com.mysql.jdbc.Driver
filters: stat
initialSize: 5
maxActive: 20
maxPoolPreparedStatementPerConnectionSize: 20
maxWait: 60000
minEvictableIdleTimeMillis: 300000
minIdle: 5
poolPreparedStatements: true
testOnBorrow: false
testOnReturn: false
testWhileIdle: true
timeBetweenEvictionRunsMillis: 60000
type: com.alibaba.druid.pool.DruidDataSource
url: jdbc:mysql://47.92.48.137:3900/zhiwen?useUnicode=true&characterEncoding=utf-8&useSSL=false
username: root
password: gkptCcYy123
validationQuery: SELECT 1 FROM DUAL
jackson:
date-format: yyyy-MM-dd HH:mm:ss
# 配置文件上传大小限制
servlet:
multipart:
max-file-size: 1500MB
max-request-size: 1500MB
# mybatis-plus相关配置
mybatis-plus:
# xml扫描
mapper-locations: classpath*:**/*Mapper.xml
global-config:
#主键类型 0:"数据库ID自增", 1:"用户输入ID",2:"全局唯一ID (数字类型唯一ID)", 3:"全局唯一ID UUID";
id-type: 0
#字段策略 0:"忽略判断",1:"非 NULL 判断"),2:"非空判断"
field-strategy: 2
db-column-underline: true
refresh-mapper: false
db-config:
logic-delete-value: 1 # 逻辑已删除值(默认为 1)
logic-not-delete-value: 0 # 逻辑未删除值(默认为 0)
#字段策略 0:"忽略判断",1:"非 NULL 判断"),2:"非空判断"
update-strategy: not_empty
configuration:
# 开启自动驼峰命名规则映射:DB的列名到Java属性驼峰命名的类似映射
map-underscore-to-camel-case: true
cache-enabled: false
jdbc-type-for-null: 'null'
# 将执行的sql打印出来
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
founder:
swagger:
title: Springboot2+MybatisPlus3+Springsecurity5+Mysql实战项目之接口文档
description: 接口文档
version: 2.0.0
# minio 参数配置
minio:
endpoint: https://47.92.48.137
accessKey: minioadmin
secretKey: minioadmin
bucketName: "miniofile"
minioHttps: true
port: 8743
package com.founder.minio;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class founderMinioApplicationTests {
@Test
void contextLoads() {
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment