提交 9b3e424b 编写于 作者: zlt2000's avatar zlt2000

重构`file-center`的自动化配置,并增加`FastDFS`的实现

上级 2e3a0308
...@@ -29,13 +29,14 @@ ...@@ -29,13 +29,14 @@
<kaptcha.version>0.0.9</kaptcha.version> <kaptcha.version>0.0.9</kaptcha.version>
<hutool.version>4.3.1</hutool.version> <hutool.version>4.3.1</hutool.version>
<mybatis-plus-boot-starter.version>3.0.6</mybatis-plus-boot-starter.version> <mybatis-plus-boot-starter.version>3.0.6</mybatis-plus-boot-starter.version>
<aliyun-sdk-oss>3.4.0</aliyun-sdk-oss> <aliyun-sdk-oss>3.4.2</aliyun-sdk-oss>
<qiniu-java-sdk>7.2.17</qiniu-java-sdk> <qiniu-java-sdk>7.2.18</qiniu-java-sdk>
<easypoi.version>4.0.0</easypoi.version> <easypoi.version>4.0.0</easypoi.version>
<spring-boot-admin.version>2.0.4</spring-boot-admin.version> <spring-boot-admin.version>2.0.4</spring-boot-admin.version>
<velocity.version>1.7</velocity.version> <velocity.version>1.7</velocity.version>
<commons-configuration.version>1.10</commons-configuration.version> <commons-configuration.version>1.10</commons-configuration.version>
<txlcn.version>5.0.2.RELEASE</txlcn.version> <txlcn.version>5.0.2.RELEASE</txlcn.version>
<fastdfs-client.version>1.26.5</fastdfs-client.version>
<platform-bom>Cairo-SR3</platform-bom> <platform-bom>Cairo-SR3</platform-bom>
<spring-cloud-alibaba-dependencies.version>0.2.1.RELEASE</spring-cloud-alibaba-dependencies.version> <spring-cloud-alibaba-dependencies.version>0.2.1.RELEASE</spring-cloud-alibaba-dependencies.version>
<spring-boot-dependencies.version>2.0.8.RELEASE</spring-boot-dependencies.version> <spring-boot-dependencies.version>2.0.8.RELEASE</spring-boot-dependencies.version>
...@@ -285,6 +286,11 @@ ...@@ -285,6 +286,11 @@
<artifactId>sharding-jdbc-spring-boot-starter</artifactId> <artifactId>sharding-jdbc-spring-boot-starter</artifactId>
<version>${sharding-sphere.version}</version> <version>${sharding-sphere.version}</version>
</dependency> </dependency>
<dependency>
<groupId>com.github.tobato</groupId>
<artifactId>fastdfs-client</artifactId>
<version>${fastdfs-client.version}</version>
</dependency>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
......
...@@ -47,16 +47,6 @@ ...@@ -47,16 +47,6 @@
<artifactId>zlt-swagger2-spring-boot-starter</artifactId> <artifactId>zlt-swagger2-spring-boot-starter</artifactId>
</dependency> </dependency>
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
</dependency>
<!-- 七牛依赖 -->
<dependency>
<groupId>com.qiniu</groupId>
<artifactId>qiniu-java-sdk</artifactId>
</dependency>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId> <artifactId>spring-boot-starter-actuator</artifactId>
...@@ -71,6 +61,22 @@ ...@@ -71,6 +61,22 @@
<groupId>io.micrometer</groupId> <groupId>io.micrometer</groupId>
<artifactId>micrometer-registry-prometheus</artifactId> <artifactId>micrometer-registry-prometheus</artifactId>
</dependency> </dependency>
<!-- 阿里云oss -->
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
</dependency>
<!-- 七牛oss -->
<dependency>
<groupId>com.qiniu</groupId>
<artifactId>qiniu-java-sdk</artifactId>
</dependency>
<!-- fastDFS -->
<dependency>
<groupId>com.github.tobato</groupId>
<artifactId>fastdfs-client</artifactId>
</dependency>
</dependencies> </dependencies>
<build> <build>
......
package com.central; package com.central;
import com.central.file.properties.FileServerProperties;
import com.central.file.properties.OssProperties;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
/** /**
...@@ -9,11 +12,10 @@ import org.springframework.cloud.client.discovery.EnableDiscoveryClient; ...@@ -9,11 +12,10 @@ import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
* @author 作者 owen E-mail: 624191343@qq.com * @author 作者 owen E-mail: 624191343@qq.com
*/ */
@EnableDiscoveryClient @EnableDiscoveryClient
@EnableConfigurationProperties(FileServerProperties.class)
@SpringBootApplication @SpringBootApplication
public class FileCenterApp { public class FileCenterApp {
public static void main(String[] args) { public static void main(String[] args) {
// 固定端口
SpringApplication.run(FileCenterApp.class, args); SpringApplication.run(FileCenterApp.class, args);
} }
} }
\ No newline at end of file
package com.central.file.config;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.central.file.model.FileInfo;
import com.central.file.properties.FileServerProperties;
import com.central.file.service.impl.AbstractIFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.aliyun.oss.OSSClient;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
/**
* 阿里云配置
*
* @author 作者 owen E-mail: 624191343@qq.com
*/
@Configuration
@ConditionalOnProperty(name = "zlt.file-server.type", havingValue = "aliyun")
public class AliyunOSSAutoConfigure {
@Autowired
private FileServerProperties fileProperties;
/**
* 阿里云文件存储client
* 只有配置了aliyun.oss.access-key才可以使用
*/
@Bean
public OSSClient ossClient() {
OSSClient ossClient = new OSSClient(fileProperties.getOss().getEndpoint()
, new DefaultCredentialProvider(fileProperties.getOss().getAccessKey(), fileProperties.getOss().getAccessKeySecret())
, null);
return ossClient;
}
@Service
public class AliyunOssServiceImpl extends AbstractIFileService {
@Autowired
private OSSClient ossClient;
@Override
protected String fileType() {
return fileProperties.getType();
}
@Override
protected void uploadFile(MultipartFile file, FileInfo fileInfo) throws Exception {
ossClient.putObject(fileProperties.getOss().getBucketName(), fileInfo.getName(), file.getInputStream());
fileInfo.setUrl(fileProperties.getOss().getDomain() + "/" + fileInfo.getName());
}
@Override
protected boolean deleteFile(FileInfo fileInfo) {
ossClient.deleteObject(fileProperties.getOss().getBucketName(), fileInfo.getName());
return true;
}
}
}
package com.central.file.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.aliyun.oss.OSSClient;
/**
* 阿里云配置
*
* @author 作者 owen E-mail: 624191343@qq.com
*/
@Configuration
public class AliyunOSSConfig {
@Value("${aliyun.oss.endpoint:xxxxx}")
private String endpoint;
@Value("${aliyun.oss.access-key:xxxxx}")
private String accessKeyId;
@Value("${aliyun.oss.accessKeySecret:xxxxx}")
private String accessKeySecret;
/**
* 阿里云文件存储client
* 只有配置了aliyun.oss.access-key才可以使用
*/
@Bean
@ConditionalOnProperty(name = "aliyun.oss.access-key", matchIfMissing = true)
public OSSClient ossClient() {
OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
return ossClient;
}
}
package com.central.file.config;
import cn.hutool.core.util.StrUtil;
import com.central.file.model.FileInfo;
import com.central.file.properties.FileServerProperties;
import com.central.file.service.impl.AbstractIFileService;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
/**
* FastDFS配置
*
* @author zlt
*/
@Configuration
@ConditionalOnProperty(name = "zlt.file-server.type", havingValue = "fastdfs")
public class FastdfsAutoConfigure {
@Autowired
private FileServerProperties fileProperties;
@Service
public class FastdfsServiceImpl extends AbstractIFileService {
@Autowired
private FastFileStorageClient storageClient;
@Override
protected String fileType() {
return fileProperties.getType();
}
@Override
protected void uploadFile(MultipartFile file, FileInfo fileInfo) throws Exception {
StorePath storePath = storageClient.uploadFile(file.getInputStream(), file.getSize(), FilenameUtils.getExtension(file.getOriginalFilename()), null);
fileInfo.setUrl(fileProperties.getFdfs().getWebUrl() + "/" + storePath.getFullPath());
fileInfo.setPath(storePath.getFullPath());
}
@Override
protected boolean deleteFile(FileInfo fileInfo) {
if (fileInfo != null && StrUtil.isNotEmpty(fileInfo.getPath())) {
StorePath storePath = StorePath.parseFromUrl(fileInfo.getPath());
storageClient.deleteFile(storePath.getGroup(), storePath.getPath());
}
return true;
}
}
}
package com.central.file.config;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.PostConstruct;
import com.central.file.service.IFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import com.central.file.model.FileType;
/**
* FileService工厂<br>
* 将各个实现类放入map
*
* @author 作者 owen E-mail: 624191343@qq.com
*/
@Configuration
public class OssServiceFactory {
private Map<FileType, IFileService> map = new EnumMap<>(FileType.class);
@Autowired
private IFileService aliyunOssServiceImpl;
@Autowired
private IFileService qiniuOssServiceImpl;
@PostConstruct
public void init() {
map.put(FileType.ALIYUN, aliyunOssServiceImpl);
map.put(FileType.QINIU, qiniuOssServiceImpl);
}
public IFileService getFileService(String fileType) {
return map.get(FileType.valueOf(fileType));
}
}
package com.central.file.config;
import com.central.common.config.DefaultPasswordConfig;
import org.springframework.context.annotation.Configuration;
/**
* @author zlt
* @date 2019/1/2
*/
@Configuration
public class PasswordConfig extends DefaultPasswordConfig {
}
package com.central.file.config; package com.central.file.config;
import org.springframework.beans.factory.annotation.Value; import com.central.file.model.FileInfo;
import org.springframework.context.annotation.Bean; import com.central.file.properties.FileServerProperties;
import org.springframework.context.annotation.Configuration; import com.central.file.service.impl.AbstractIFileService;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone; import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager; import org.springframework.beans.factory.annotation.Autowired;
import com.qiniu.storage.UploadManager; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import com.qiniu.util.Auth; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* 七牛云配置 import com.qiniu.common.Zone;
* import com.qiniu.storage.BucketManager;
* @author 作者 owen E-mail: 624191343@qq.com import com.qiniu.storage.UploadManager;
*/ import com.qiniu.util.Auth;
@Configuration import org.springframework.stereotype.Service;
public class QiniuOSSConfig { import org.springframework.web.multipart.MultipartFile;
@Value("${qiniu.oss.access-key:xxxxx}")
private String accessKeyId; /**
@Value("${qiniu.oss.accessKeySecret:xxxxx}") * 七牛云配置
private String accessKeySecret; *
* @author 作者 owen E-mail: 624191343@qq.com
/** */
* 华东机房 @Configuration
*/ @ConditionalOnProperty(name = "zlt.file-server.type", havingValue = "qiniu")
@Bean public class QiniuOSSAutoConfigure {
public com.qiniu.storage.Configuration qiniuConfig() { @Autowired
return new com.qiniu.storage.Configuration(Zone.zone2()); private FileServerProperties fileProperties;
}
/**
/** * 华东机房
* 构建一个七牛上传工具实例 */
*/ @Bean
@Bean public com.qiniu.storage.Configuration qiniuConfig() {
public UploadManager uploadManager() { return new com.qiniu.storage.Configuration(Zone.zone2());
return new UploadManager(qiniuConfig()); }
}
/**
/** * 构建一个七牛上传工具实例
* 认证信息实例 */
* @Bean
* @return public UploadManager uploadManager() {
*/ return new UploadManager(qiniuConfig());
@Bean }
public Auth auth() {
return Auth.create(accessKeyId, accessKeySecret); /**
} * 认证信息实例
*
/** * @return
* 构建七牛空间管理实例 */
*/ @Bean
@Bean public Auth auth() {
public BucketManager bucketManager() { return Auth.create(fileProperties.getOss().getAccessKey(), fileProperties.getOss().getAccessKeySecret());
return new BucketManager(auth(), qiniuConfig()); }
}
} /**
* 构建七牛空间管理实例
*/
@Bean
public BucketManager bucketManager() {
return new BucketManager(auth(), qiniuConfig());
}
@Service
public class QiniuOssServiceImpl extends AbstractIFileService {
@Autowired
private UploadManager uploadManager;
@Autowired
private BucketManager bucketManager;
@Autowired
private Auth auth;
@Override
protected String fileType() {
return fileProperties.getType();
}
@Override
protected void uploadFile(MultipartFile file, FileInfo fileInfo) throws Exception {
// 调用put方法上传
uploadManager.put(file.getBytes(), fileInfo.getName(), auth.uploadToken(fileProperties.getOss().getBucketName()));
fileInfo.setUrl(fileProperties.getOss().getEndpoint() + "/" + fileInfo.getName());
fileInfo.setPath(fileProperties.getOss().getEndpoint() + "/" + fileInfo.getName());
}
@Override
protected boolean deleteFile(FileInfo fileInfo) {
try {
Response response = bucketManager.delete(fileProperties.getOss().getBucketName(), fileInfo.getPath());
int retry = 0;
while (response.needRetry() && retry++ < 3) {
response = bucketManager.delete(fileProperties.getOss().getBucketName(), fileInfo.getPath());
}
} catch (QiniuException e) {
return false;
}
return true;
}
}
}
...@@ -4,7 +4,6 @@ import java.util.Map; ...@@ -4,7 +4,6 @@ import java.util.Map;
import com.central.common.model.Result; import com.central.common.model.Result;
import com.central.file.service.IFileService; import com.central.file.service.IFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PathVariable;
...@@ -14,21 +13,19 @@ import org.springframework.web.bind.annotation.RestController; ...@@ -14,21 +13,19 @@ import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import com.central.common.model.PageResult; import com.central.common.model.PageResult;
import com.central.file.config.OssServiceFactory;
import com.central.file.model.FileInfo; import com.central.file.model.FileInfo;
import com.central.file.model.FileType;
import javax.annotation.Resource;
/** /**
* 文件上传 同步oss db双写 目前仅实现了阿里云,七牛云 * 文件上传
* 参考src/main/view/upload.html
* *
* @author 作者 owen E-mail: 624191343@qq.com * @author 作者 owen E-mail: 624191343@qq.com
*/ */
@RestController @RestController
public class FileController { public class FileController {
@Resource
@Autowired private IFileService fileService;
private OssServiceFactory fileServiceFactory;
/** /**
* 文件上传 * 文件上传
...@@ -40,8 +37,6 @@ public class FileController { ...@@ -40,8 +37,6 @@ public class FileController {
*/ */
@PostMapping("/files-anon") @PostMapping("/files-anon")
public FileInfo upload(@RequestParam("file") MultipartFile file) throws Exception { public FileInfo upload(@RequestParam("file") MultipartFile file) throws Exception {
String fileType = FileType.QINIU.toString();
IFileService fileService = fileServiceFactory.getFileService(fileType);
return fileService.upload(file); return fileService.upload(file);
} }
...@@ -53,11 +48,7 @@ public class FileController { ...@@ -53,11 +48,7 @@ public class FileController {
@DeleteMapping("/files/{id}") @DeleteMapping("/files/{id}")
public Result delete(@PathVariable String id) { public Result delete(@PathVariable String id) {
try { try {
FileInfo fileInfo = fileServiceFactory.getFileService(FileType.QINIU.toString()).getById(id); fileService.delete(id);
if (fileInfo != null) {
IFileService fileService = fileServiceFactory.getFileService(fileInfo.getSource());
fileService.removeById(fileInfo);
}
return Result.succeed("操作成功"); return Result.succeed("操作成功");
} catch (Exception ex) { } catch (Exception ex) {
return Result.failed("操作失败"); return Result.failed("操作失败");
...@@ -72,6 +63,6 @@ public class FileController { ...@@ -72,6 +63,6 @@ public class FileController {
*/ */
@GetMapping("/files") @GetMapping("/files")
public PageResult<FileInfo> findFiles(@RequestParam Map<String, Object> params) { public PageResult<FileInfo> findFiles(@RequestParam Map<String, Object> params) {
return fileServiceFactory.getFileService(FileType.QINIU.toString()).findList(params); return fileService.findList(params);
} }
} }
package com.central.file.model;
/**
* 仅支持阿里云 oss ,七牛云等
*
* @author 作者 owen E-mail: 624191343@qq.com
*/
public enum FileType {
//七牛
QINIU,
//阿里云
ALIYUN
}
package com.central.file.properties;
import lombok.Getter;
import lombok.Setter;
/**
* @author zlt
*/
@Setter
@Getter
public class FdfsProperties {
/**
* fastdfs的http访问地址
*/
private String webUrl;
}
package com.central.file.properties;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
/**
* @author zlt
*/
@Setter
@Getter
@ConfigurationProperties(prefix = "zlt.file-server")
@RefreshScope
public class FileServerProperties {
/**
* 为以下3个值,指定不同的自动化配置
* qiniu:七牛oss
* aliyun:阿里云oss
* fastdfs:本地部署的fastDFS
*/
private String type;
/**
* oss配置
*/
OssProperties oss = new OssProperties();
/**
* fastDFS配置
*/
FdfsProperties fdfs = new FdfsProperties();
}
package com.central.file.properties;
import lombok.Getter;
import lombok.Setter;
/**
* @author zlt
*/
@Setter
@Getter
public class OssProperties {
/**
* 密钥key
*/
private String accessKey;
/**
* 密钥密码
*/
private String accessKeySecret;
/**
* 端点
*/
private String endpoint;
/**
* bucket名称
*/
private String bucketName;
/**
* 说明
*/
private String domain;
}
...@@ -9,7 +9,7 @@ import org.springframework.web.multipart.MultipartFile; ...@@ -9,7 +9,7 @@ import org.springframework.web.multipart.MultipartFile;
import com.central.file.model.FileInfo; import com.central.file.model.FileInfo;
/** /**
* 文件service 目前仅支持阿里云oss,七牛云 * 文件service
* *
* @author 作者 owen E-mail: 624191343@qq.com * @author 作者 owen E-mail: 624191343@qq.com
*/ */
...@@ -17,4 +17,6 @@ public interface IFileService extends IService<FileInfo> { ...@@ -17,4 +17,6 @@ public interface IFileService extends IService<FileInfo> {
FileInfo upload(MultipartFile file ) throws Exception; FileInfo upload(MultipartFile file ) throws Exception;
PageResult<FileInfo> findList(Map<String, Object> params); PageResult<FileInfo> findList(Map<String, Object> params);
void delete(String id);
} }
...@@ -11,7 +11,6 @@ import org.springframework.web.multipart.MultipartFile; ...@@ -11,7 +11,6 @@ import org.springframework.web.multipart.MultipartFile;
import com.central.common.model.PageResult; import com.central.common.model.PageResult;
import com.central.file.mapper.FileMapper; import com.central.file.mapper.FileMapper;
import com.central.file.model.FileInfo; import com.central.file.model.FileInfo;
import com.central.file.model.FileType;
import com.central.file.service.IFileService; import com.central.file.service.IFileService;
import com.central.file.utils.FileUtil; import com.central.file.utils.FileUtil;
...@@ -19,56 +18,73 @@ import lombok.extern.slf4j.Slf4j; ...@@ -19,56 +18,73 @@ import lombok.extern.slf4j.Slf4j;
/** /**
* AbstractIFileService 抽取类 * AbstractIFileService 抽取类
* 根据filetype 实例化具体oss对象 * 根据zlt.file-server.type 实例化具体对象
* *
* @author 作者 owen E-mail: 624191343@qq.com * @author 作者 owen E-mail: 624191343@qq.com
*/ */
@Slf4j @Slf4j
public abstract class AbstractIFileService extends ServiceImpl<FileMapper, FileInfo> implements IFileService { public abstract class AbstractIFileService extends ServiceImpl<FileMapper, FileInfo> implements IFileService {
@Override private static final String FILE_SPLIT = ".";
public FileInfo upload(MultipartFile file ) throws Exception {
FileInfo fileInfo = FileUtil.getFileInfo(file);
FileInfo oldFileInfo = baseMapper.selectById(fileInfo.getId());
if (oldFileInfo != null) {
return oldFileInfo;
}
if (!fileInfo.getName().contains(".")) {
throw new IllegalArgumentException("缺少后缀名");
}
uploadFile(file, fileInfo);
fileInfo.setSource(fileType().name());// 设置文件来源
baseMapper.insert(fileInfo);// 将文件信息保存到数据库
return fileInfo; @Override
} public FileInfo upload(MultipartFile file) throws Exception {
FileInfo fileInfo = FileUtil.getFileInfo(file);
FileInfo oldFileInfo = baseMapper.selectById(fileInfo.getId());
if (oldFileInfo != null) {
return oldFileInfo;
}
if (!fileInfo.getName().contains(FILE_SPLIT)) {
throw new IllegalArgumentException("缺少后缀名");
}
uploadFile(file, fileInfo);
// 设置文件来源
fileInfo.setSource(fileType());
// 将文件信息保存到数据库
baseMapper.insert(fileInfo);
/** return fileInfo;
* 文件来源 }
*
* @return
*/
protected abstract FileType fileType();
/** /**
* 上传文件 * 文件来源
* *
* @param file * @return
* @param fileInfo */
*/ protected abstract String fileType();
protected abstract void uploadFile(MultipartFile file, FileInfo fileInfo) throws Exception;
/** /**
* 删除文件资源 * 上传文件
* *
* @param fileInfo * @param file
* @return * @param fileInfo
*/ */
protected abstract boolean deleteFile(FileInfo fileInfo); protected abstract void uploadFile(MultipartFile file, FileInfo fileInfo) throws Exception;
@Override /**
public PageResult<FileInfo> findList(Map<String, Object> params){ * 删除文件
Page<FileInfo> page = new Page<>(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit")); * @param id 文件id
*/
@Override
public void delete(String id) {
FileInfo fileInfo = baseMapper.selectById(id);
if (fileInfo != null) {
baseMapper.deleteById(fileInfo.getId());
this.deleteFile(fileInfo);
}
}
/**
* 删除文件资源
*
* @param fileInfo
* @return
*/
protected abstract boolean deleteFile(FileInfo fileInfo);
@Override
public PageResult<FileInfo> findList(Map<String, Object> params) {
Page<FileInfo> page = new Page<>(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit"));
List<FileInfo> list = baseMapper.findList(page, params); List<FileInfo> list = baseMapper.findList(page, params);
return PageResult.<FileInfo>builder().data(list).code(0).count(page.getTotal()).build(); return PageResult.<FileInfo>builder().data(list).code(0).count(page.getTotal()).build();
} }
} }
package com.central.file.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import com.aliyun.oss.OSSClient;
import com.central.file.model.FileInfo;
import com.central.file.model.FileType;
/**
* 阿里云oss存储文件
*
* @author 作者 owen E-mail: 624191343@qq.com
*/
@Service("aliyunOssServiceImpl")
public class AliyunOssServiceImplI extends AbstractIFileService {
@Autowired
private OSSClient ossClient;
@Value("${aliyun.oss.bucketName:xxxxx}")
private String bucketName;
@Value("${aliyun.oss.domain:xxxxx}")
private String domain;
@Override
protected FileType fileType() {
return FileType.ALIYUN;
}
@Override
protected void uploadFile(MultipartFile file, FileInfo fileInfo) throws Exception {
ossClient.putObject(bucketName, fileInfo.getName(), file.getInputStream());
fileInfo.setUrl(domain + "/" + fileInfo.getName());
}
@Override
protected boolean deleteFile(FileInfo fileInfo) {
ossClient.deleteObject(bucketName, fileInfo.getName());
return true;
}
}
package com.central.file.service.impl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import com.central.file.model.FileInfo;
import com.central.file.model.FileType;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
/**
* 七牛云oss存储文件
*
* @author 作者 owen E-mail: 624191343@qq.com
*/
@Slf4j
@Service("qiniuOssServiceImpl")
public class QiniuOssServiceImplI extends AbstractIFileService implements InitializingBean {
@Autowired
private UploadManager uploadManager;
@Autowired
private BucketManager bucketManager;
@Autowired
private Auth auth;
@Value("${qiniu.oss.bucketName:xxxxx}")
private String bucket;
@Value("${qiniu.oss.endpoint:xxxxx}")
private String endpoint;
private StringMap putPolicy;
@Override
protected FileType fileType() {
return FileType.QINIU;
}
@Override
protected void uploadFile(MultipartFile file, FileInfo fileInfo) throws Exception {
// 调用put方法上传
uploadManager.put(file.getBytes(), fileInfo.getName(), auth.uploadToken(bucket));
fileInfo.setUrl(endpoint + "/" + fileInfo.getName());
fileInfo.setPath(endpoint + "/" + fileInfo.getName());
}
@Override
protected boolean deleteFile(FileInfo fileInfo) {
try {
Response response = bucketManager.delete(this.bucket, fileInfo.getPath());
int retry = 0;
while (response.needRetry() && retry++ < 3) {
response = bucketManager.delete(bucket, fileInfo.getPath());
}
} catch (QiniuException e) {
return false;
}
return true;
}
@Override
public void afterPropertiesSet() throws Exception {
this.putPolicy = new StringMap();
putPolicy.put("returnBody",
"{\"key\":\"$(key)\",\"hash\":\"$(etag)\",\"bucket\":\"$(bucket)\",\"width\":$(imageInfo.width), \"height\":${imageInfo.height}}");
}
}
...@@ -24,7 +24,8 @@ public class FileUtil { ...@@ -24,7 +24,8 @@ public class FileUtil {
public static FileInfo getFileInfo(MultipartFile file) throws Exception { public static FileInfo getFileInfo(MultipartFile file) throws Exception {
String md5 = fileMd5(file.getInputStream()); String md5 = fileMd5(file.getInputStream());
FileInfo fileInfo = new FileInfo(); FileInfo fileInfo = new FileInfo();
fileInfo.setId(md5);// 将文件的md5设置为文件表的id // 将文件的md5设置为文件表的id
fileInfo.setId(md5);
fileInfo.setName(file.getOriginalFilename()); fileInfo.setName(file.getOriginalFilename());
fileInfo.setContentType(file.getContentType()); fileInfo.setContentType(file.getContentType());
fileInfo.setIsImg(fileInfo.getContentType().startsWith("image/")); fileInfo.setIsImg(fileInfo.getContentType().startsWith("image/"));
......
#aliyun:
# oss:
# access-key: 你的密钥
# accessKeySecret: 你的密钥
# endpoint: 你的端点
# bucketName: 你的名称
# domain: 你的说明
qiniu:
oss:
access-key: tpi8mObnfzZi4ggBX8Bw7zydjoTQ0WeML3RkPKsX
accessKeySecret: HZBXmSyUTy-haYp0KbBTtsil-GoKjVS2kDKT8Yow
endpoint: http://pkqtmn0p1.bkt.clouddn.com
bucketName: public-oss
spring: spring:
datasource: datasource:
url: jdbc:mysql://${zlt.datasource.ip}:3306/file_center?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull url: jdbc:mysql://${zlt.datasource.ip}:3306/file_center?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull
...@@ -27,10 +12,28 @@ mybatis-plus: ...@@ -27,10 +12,28 @@ mybatis-plus:
global-config: global-config:
db-config: db-config:
id-type: INPUT id-type: INPUT
zlt: zlt:
file-server:
type: fastdfs
fdfs:
web-url: ${zlt.fdfs.web-url}
#oss配置
#oss:
# access-key: tpi8mObnfzZi4ggBX8Bw7zydjoTQ0WeML3RkPKsX
# accessKeySecret: HZBXmSyUTy-haYp0KbBTtsil-GoKjVS2kDKT8Yow
# endpoint: http://pkqtmn0p1.bkt.clouddn.com
# bucketName: public-oss
# domain:
swagger: swagger:
enabled: true enabled: true
title: 文件中心 title: 文件中心
description: 文件中心接口文档 description: 文件中心接口文档
version: 1.0 version: 1.0
base-package: com.central.file.controller base-package: com.central.file.controller
\ No newline at end of file
#fastDFS配置
fdfs:
soTimeout: 1500
connectTimeout: 600
trackerList: ${zlt.fdfs.trackerList}
\ No newline at end of file
...@@ -14,4 +14,8 @@ zlt.elasticsearch.cluster-name=my-es ...@@ -14,4 +14,8 @@ zlt.elasticsearch.cluster-name=my-es
zlt.elasticsearch.cluster-nodes=192.168.28.130:9300 zlt.elasticsearch.cluster-nodes=192.168.28.130:9300
##### sentinel配置 ##### sentinel配置
zlt.sentinel.dashboard=127.0.0.1:6999 zlt.sentinel.dashboard=127.0.0.1:6999
\ No newline at end of file
##### fastDFS配置
zlt.fdfs.trackerList=192.168.28.130:22122
zlt.fdfs.web-url=192.168.28.130
\ No newline at end of file
...@@ -14,4 +14,8 @@ zlt.elasticsearch.cluster-name=my-es ...@@ -14,4 +14,8 @@ zlt.elasticsearch.cluster-name=my-es
zlt.elasticsearch.cluster-nodes=47.107.114.25:9300 zlt.elasticsearch.cluster-nodes=47.107.114.25:9300
##### sentinel配置 ##### sentinel配置
zlt.sentinel.dashboard=120.78.94.191:6999 zlt.sentinel.dashboard=120.78.94.191:6999
\ No newline at end of file
##### fastDFS配置
zlt.fdfs.trackerList[0]=47.107.114.25:22122
zlt.fdfs.web-url=47.107.114.25
\ No newline at end of file
...@@ -14,4 +14,8 @@ zlt.elasticsearch.cluster-name=my-es ...@@ -14,4 +14,8 @@ zlt.elasticsearch.cluster-name=my-es
zlt.elasticsearch.cluster-nodes=47.107.114.25:9300 zlt.elasticsearch.cluster-nodes=47.107.114.25:9300
##### sentinel配置 ##### sentinel配置
zlt.sentinel.dashboard=120.78.94.191:6999 zlt.sentinel.dashboard=120.78.94.191:6999
\ No newline at end of file
##### fastDFS配置
zlt.fdfs.trackerList[0]=47.107.114.25:22122
zlt.fdfs.web-url=47.107.114.25
\ No newline at end of file
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册