init project v1.0.0

This commit is contained in:
zlt
2019-01-19 15:31:26 +08:00
parent 5c1cdaa54e
commit 19fecc3b05
728 changed files with 65634 additions and 0 deletions
@@ -0,0 +1,19 @@
package com.central;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
/**
* @author zlt
* 文件中心
*/
@EnableDiscoveryClient
@SpringBootApplication
public class FileCenterApp {
public static void main(String[] args) {
// 固定端口
SpringApplication.run(FileCenterApp.class, args);
}
}
@@ -0,0 +1,34 @@
package com.central.file.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
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 zlt
* 阿里云配置
*/
@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;
}
}
@@ -0,0 +1,14 @@
package com.central.file.config;
import com.central.common.config.DefaultAsycTaskConfig;
import org.springframework.context.annotation.Configuration;
/**
* @author zlt
* 线程池配置、启用异步
* @Async quartz 需要使用
*/
@Configuration
public class AsycTaskExecutorConfig extends DefaultAsycTaskConfig {
}
@@ -0,0 +1,15 @@
package com.central.file.config;
import com.central.db.config.DefaultMybatisPlusConfig;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Configuration;
/**
* @author zlt
* @date 2018/12/10
*/
@Configuration
@MapperScan({"com.central.file.mapper*"})
public class MybatisPlusConfig extends DefaultMybatisPlusConfig {
}
@@ -0,0 +1,38 @@
package com.central.file.config;
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;
/**
* @author zlt
* FileService工厂<br>
* 将各个实现类放入map
*/
@Configuration
public class OssServiceFactory {
private Map<FileType, IFileService> map = new HashMap<>();
@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));
}
}
@@ -0,0 +1,12 @@
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 {
}
@@ -0,0 +1,56 @@
package com.central.file.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.qiniu.common.Zone;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
/**
* @author zlt
* 七牛云配置
*/
@Configuration
public class QiniuOSSConfig {
@Value("${qiniu.oss.access-key:xxxxx}")
private String accessKeyId;
@Value("${qiniu.oss.accessKeySecret:xxxxx}")
private String accessKeySecret;
/**
* 华东机房
*/
@Bean
public com.qiniu.storage.Configuration qiniuConfig() {
return new com.qiniu.storage.Configuration(Zone.zone2());
}
/**
* 构建一个七牛上传工具实例
*/
@Bean
public UploadManager uploadManager() {
return new UploadManager(qiniuConfig());
}
/**
* 认证信息实例
*
* @return
*/
@Bean
public Auth auth() {
return Auth.create(accessKeyId, accessKeySecret);
}
/**
* 构建七牛空间管理实例
*/
@Bean
public BucketManager bucketManager() {
return new BucketManager(auth(), qiniuConfig());
}
}
@@ -0,0 +1,77 @@
package com.central.file.controller;
import java.util.Map;
import com.central.common.model.Result;
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.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.central.common.model.PageResult;
import com.central.file.config.OssServiceFactory;
import com.central.file.model.FileInfo;
import com.central.file.model.FileType;
/**
* 文件上传 同步oss db双写 目前仅实现了阿里云,七牛云
* 参考src/main/view/upload.html
*
* @author zlt
*/
@RestController
public class FileController {
@Autowired
private OssServiceFactory fileServiceFactory;
/**
* 文件上传
* 根据fileType选择上传方式
*
* @param file
* @return
* @throws Exception
*/
@PostMapping("/files-anon")
public FileInfo upload(@RequestParam("file") MultipartFile file) throws Exception {
String fileType = FileType.QINIU.toString();
IFileService fileService = fileServiceFactory.getFileService(fileType);
return fileService.upload(file);
}
/**
* 文件删除
*
* @param id
*/
@DeleteMapping("/files/{id}")
public Result delete(@PathVariable String id) {
try {
FileInfo fileInfo = fileServiceFactory.getFileService(FileType.QINIU.toString()).getById(id);
if (fileInfo != null) {
IFileService fileService = fileServiceFactory.getFileService(fileInfo.getSource());
fileService.removeById(fileInfo);
}
return Result.succeed("操作成功");
} catch (Exception ex) {
return Result.failed("操作失败");
}
}
/**
* 文件查询
*
* @param params
* @return
*/
@GetMapping("/files")
public PageResult<FileInfo> findFiles(@RequestParam Map<String, Object> params) {
return fileServiceFactory.getFileService(FileType.QINIU.toString()).findList(params);
}
}
@@ -0,0 +1,19 @@
package com.central.file.mapper;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.central.db.mapper.SuperMapper;
import com.central.file.model.FileInfo;
import org.apache.ibatis.annotations.Param;
/**
* 上传存储db
*
* @author zlt
*/
public interface FileMapper extends SuperMapper<FileInfo> {
List<FileInfo> findList(Page<FileInfo> page, @Param("f") Map<String, Object> params);
}
@@ -0,0 +1,63 @@
package com.central.file.model;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.io.Serializable;
import java.util.Date;
/**
* @author zlt
* file实体类
*/
@Data
@EqualsAndHashCode(callSuper = false)
@TableName("file_info")
public class FileInfo extends Model<FileInfo> {
private static final long serialVersionUID = -1438078028040922174L;
@TableId
private String id;
/**
* 原始文件名
*/
private String name;
/**
* 是否图片
*/
private Boolean isImg;
/**
* 上传文件类型
*/
private String contentType;
/**
* 文件大小
*/
private long size;
/**
* 冗余字段
*/
private String path;
/**
* oss访问路径 oss需要设置公共读
*/
private String url;
/**
* FileType字段
*/
private String source;
@TableField(fill = FieldFill.INSERT)
private Date createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;
@Override
protected Serializable pkVal() {
return this.id;
}
}
@@ -0,0 +1,12 @@
package com.central.file.model;
/**
* @author zlt
* 仅支持阿里云 oss ,七牛云等
*/
public enum FileType {
//七牛
QINIU,
//阿里云
ALIYUN
}
@@ -0,0 +1,19 @@
package com.central.file.service;
import java.util.Map;
import com.baomidou.mybatisplus.extension.service.IService;
import com.central.common.model.PageResult;
import org.springframework.web.multipart.MultipartFile;
import com.central.file.model.FileInfo;
/**
* @author zlt
* 文件service 目前仅支持阿里云oss,七牛云
*/
public interface IFileService extends IService<FileInfo> {
FileInfo upload(MultipartFile file ) throws Exception;
PageResult<FileInfo> findList(Map<String, Object> params);
}
@@ -0,0 +1,74 @@
package com.central.file.service.impl;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.central.common.model.SysUser;
import org.apache.commons.collections4.MapUtils;
import org.springframework.web.multipart.MultipartFile;
import com.central.common.model.PageResult;
import com.central.file.mapper.FileMapper;
import com.central.file.model.FileInfo;
import com.central.file.model.FileType;
import com.central.file.service.IFileService;
import com.central.file.utils.FileUtil;
import lombok.extern.slf4j.Slf4j;
/**
* @author zlt
* AbstractIFileService 抽取类
* 根据filetype 实例化具体oss对象
*/
@Slf4j
public abstract class AbstractIFileService extends ServiceImpl<FileMapper, FileInfo> implements IFileService {
@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(".")) {
throw new IllegalArgumentException("缺少后缀名");
}
uploadFile(file, fileInfo);
fileInfo.setSource(fileType().name());// 设置文件来源
baseMapper.insert(fileInfo);// 将文件信息保存到数据库
return fileInfo;
}
/**
* 文件来源
*
* @return
*/
protected abstract FileType fileType();
/**
* 上传文件
*
* @param file
* @param fileInfo
*/
protected abstract void uploadFile(MultipartFile file, FileInfo fileInfo) throws Exception;
/**
* 删除文件资源
*
* @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);
return PageResult.<FileInfo>builder().data(list).code(0).count(page.getTotal()).build();
}
}
@@ -0,0 +1,42 @@
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.mapper.FileMapper;
import com.central.file.model.FileInfo;
import com.central.file.model.FileType;
/**
* @author zlt
* 阿里云oss存储文件
*/
@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;
}
}
@@ -0,0 +1,80 @@
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;
/**
* @author zlt
* 七牛云oss存储文件
*/
@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;
}
/**
* 获取上传凭证
*
* @return
*/
private String getUploadToken() {
return this.auth.uploadToken(bucket, null, 3600, putPolicy);
}
@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}}");
}
}
@@ -0,0 +1,76 @@
package com.central.file.utils;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import com.central.file.model.FileInfo;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.web.multipart.MultipartFile;
/**
* @author zlt
* 文件工具类
*/
public class FileUtil {
public static FileInfo getFileInfo(MultipartFile file) throws Exception {
String md5 = fileMd5(file.getInputStream());
FileInfo fileInfo = new FileInfo();
fileInfo.setId(md5);// 将文件的md5设置为文件表的id
fileInfo.setName(file.getOriginalFilename());
fileInfo.setContentType(file.getContentType());
fileInfo.setIsImg(fileInfo.getContentType().startsWith("image/"));
fileInfo.setSize(file.getSize());
fileInfo.setCreateTime(new Date());
return fileInfo;
}
/**
* 文件的md5
*
* @param inputStream
* @return
*/
public static String fileMd5(InputStream inputStream) {
try {
return DigestUtils.md5Hex(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static String saveFile(MultipartFile file, String path) {
try {
File targetFile = new File(path);
if (targetFile.exists()) {
return path;
}
if (!targetFile.getParentFile().exists()) {
targetFile.getParentFile().mkdirs();
}
file.transferTo(targetFile);
return path;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static boolean deleteFile(String pathname) {
File file = new File(pathname);
if (file.exists()) {
boolean flag = file.delete();
if (flag) {
File[] files = file.getParentFile().listFiles();
if (files == null || files.length == 0) {
file.getParentFile().delete();
}
}
return flag;
}
return false;
}
}