SpringBoot 使用minio 分布式文件服务
依赖
<!--minio文件系统-->
<dependency>
<groupId>io.minio</groupId>
<artifactId>minio</artifactId>
<version>6.0.2</version>
</dependency>
<!--Lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>provided</scope>
</dependency>
1、在application.yml中配置
# 文件系统
minio:
url: http://127.0.0.1:9000
access-key: xxxxxxxxx
secret-key: xxxxxxxx
bucket-name: zdrjy
2、注入配置到properties
@Data
@Configuration
@ConfigurationProperties(prefix = "minio")
public class MinioProperties {
/**
* minio 服务地址 http://ip:port
*/
private String url;
/**
* 用户名
*/
private String accessKey;
/**
* 密码
*/
private String secretKey;
/**
* 桶名称
*/
private String bucketName;
}
3、初始化 MinioClient 自动注入到 spring 容器
@AllArgsConstructor
@EnableConfigurationProperties({MinioProperties.class})
public class MinioAutoConfiguration {
private final MinioProperties properties;
@Bean
@ConditionalOnMissingBean(MinioTemplate.class)
@ConditionalOnProperty(name = "minio.url")
MinioClient minioClient() {
return new MinioClient(
properties.getUrl(),
properties.getAccessKey(),
properties.getSecretKey()
);
}
}
4、创建Service
@Slf4j
@Component
@AllArgsConstructor
public class MinioStorageService {
private final MinioClient minioClient;
private final MinioProperties minioProperties;
/**
* 上传文件
*/
public String uploadFile(byte[] data, String filePath) {
InputStream inputStream = new ByteArrayInputStream(data);
String path;
try {
client.putObject(minioClient.getBucketName(), filePath, inputStream, inputStream.available(), getContextType(fileName));
path = filePath;
} catch (Exception e) {
log.error("=====minio:"+e.getMessage());
}
return path;
}
/**
* 删除文件
*/
public boolean delete(String filePath) {
try {
client.removeObject(minioClient.getBucketName(),filePath);
return true;
} catch (Exception e) {
log.error("====minio:删除失败,"+e.getMessage());
}
return false;
}
public String getContextType(String path){
String suffix = path.substring(path.lastIndexOf(".") + 1 );
String type = "application/octet-stream";
if(suffix.equals("jpg")||suffix.equals("jpeg")||suffix.equals("png")||suffix.equals("bmp")||suffix.equals("gif")){
type = "image/jpeg";
}
return type;
}
}
5、最后 Controller
@RestController
@RequestMapping("oss")
@AllArgsConstructor
public class OssController {
private final MinioStorageService minioStorageService;
/**
* 上传文件
*/
@RequestMapping("/upload")
public R upload(@RequestParam("file") MultipartFile file) throws Exception {
if (file.isEmpty()) {
throw new RRException("上传文件不能为空");
}
//上传文件
String path = "/psm_memory_service/picture/fore-end/"+file.getOriginalFilename();
String url = minioStorageService.uploadFile(file.getBytes(),path);
return R.ok().put("url", url);
}
/**
* 删除
*/
@RequestMapping("/delete/{id}")
public R delete(@PathVariable("id") String id){
SysOss oss = sysOssService.getById(id);
ossFactory.build().delete(oss.getUrl());
sysOssService.removeById(id);
return R.ok();
}
}
具体CURD源码可以看 https://github.com/yzcheng90/X-SpringBoot