centos7安装minio集成spring boot

目录

一、背景

二、安装教程

三、springboot项目集成minio

1.引入maven依赖

2.yml配置

3.minio配置类

4.minio工具类

一、背景

        项目中需要有上传、下载、预览文件的需求,要求不准在服务器进行本地文件写入,必须要写入至统一对象存储中,且minio有着高度可扩展、高可用性,极高的性能,开源,因此准备引入开源且功能完善强大的文件存储服务系统minio。

        MinIO专为部署在任何地方而构建的公共云或私有云、裸机基础架构、编排环境和边缘基础架构,虽然轻量,却拥有着不错的性能。

二、安装教程

#创建相关文件夹
mkdir -p /home/minio
mkdir -p /home/minio/bin
mkdir -p /home/minio/data
 
 
#进入上面创建的bin目录下
cd /home/minio/bin
 
#下载minio(选择适合自己系统的版本,本文使用的是Linux版本)
wget https://dl.minio.org.cn/server/minio/release/linux-amd64/minio
 

继续执行命令授权

#进入/home/minio/bin目录
cd /home/minio/bin
 
#对刚刚下载的minio文件进行授权
chmod +x minio

执行命令将minio添加程Linux系统服务,这样以后就可以支持systemctl命令启动

#进入系统目录
cd /etc/systemd/system
 
#创建文件minio.service
vim minio.service
 
#编辑文件,将以下内容拷贝到minio.service文件中
[Unit]
Description=Minio
Wants=network-online.target
After=network-online.target
AssertFileIsExecutable=/home/minio/bin/minio
 
[Service]
WorkingDirectory=/home/minio/
PermissionsStartOnly=true
ExecStart=/home/minio/bin/minio server /home/minio/data
ExecReload=/bin/ki11-S HUP $MAINPID
ExecStop=/bin/ki11 -S QUIT $MAINPID
PrivateTmp=true
 
[Install]
WantedBy=multi-user.target

完成上述步骤后,可通过以下命令启停minio等

#启动minio
systemctl start minio
 
#停止minio
systemctl stop minio
 
#查看minio状态
systemctl status minio

至此minio已经安装完成;

mino后台管理访问地址:ip:44373;默认账号:minioadmin/minioadmin

使用systemctl status minio命令查看下minio状态:

三、springboot项目集成minio

1.引入maven依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-amqp</artifactId>
</dependency>

2.yml配置

spring:
  servlet:
    minio:
      accesskey: minioadmin
      secretkey: minioadmin
      miniourl: http://ip:9000 #ip替换为minio服务的ip

3.minio配置类

import io.minio.MinioClient;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
 
/**
 * minio配置类
 * 
 * @author 
 */
@Data
@Configuration
@ConfigurationProperties(value = "spring.servlet.minio")
public class MinioConfig
{
	private String accesskey;
	private String secretkey;
	private String miniourl;
	@Bean
	public MinioClient minioClient(){
		return MinioClient.builder()
				.endpoint(miniourl)
				.credentials(accesskey,secretkey)
				.build();
	}
}

4.minio工具类

/**
 * 文件上传工具类
 * @author hongwentao
 */
@Component
public class MinioUtils
{
 
	@Resource
	private MinioClient minioClient;
 
	@Autowired
	private MinioConfig minioConfig;
 
	/**
	 * @param name
	 *            名字
	 * @Description 判断bucket是否存在,不存在则创建
	 */
	public boolean existBucket(String name)
	{
		boolean exists;
		try
		{
			exists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(name).build());
			if (!exists)
			{
				minioClient.makeBucket(MakeBucketArgs.builder().bucket(name).build());
				exists = true;
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
			exists = false;
		}
		return exists;
	}
 
	/**
	 * @param bucketName
	 *            存储bucket名称
	 * @Description 创建存储bucket
	 */
	public Boolean makeBucket(String bucketName)
	{
		if(this.existBucket(bucketName)){
			return true;
		}
		try
		{
			minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
		}
		catch (Exception e)
		{
			e.printStackTrace();
			return false;
		}
		return true;
	}
 
	/**
	 * @param bucketName
	 *            存储bucket名称
	 * @Description 删除存储bucket
	 */
	public Boolean removeBucket(String bucketName)
	{
		if(!this.existBucket(bucketName)){
			return true;
		}
		try
		{
			minioClient.removeBucket(RemoveBucketArgs.builder().bucket(bucketName).build());
		}
		catch (Exception e)
		{
			e.printStackTrace();
			return false;
		}
		return true;
	}
 
	/**
	 * @param fileName
	 *            文件名称
	 * @param time
	 *            时间
	 * @Description 获取上传临时签名
	 */
	@SneakyThrows
	public Map getPolicy(String fileName, ZonedDateTime time, String bucketName)
	{
		PostPolicy postPolicy = new PostPolicy(bucketName, time);
		postPolicy.addEqualsCondition("key", fileName);
		try
		{
			Map<String, String> map = minioClient.getPresignedPostFormData(postPolicy);
			HashMap<String, String> map1 = new HashMap<>();
			map.forEach((k, v) -> {
				map1.put(k.replaceAll("-", ""), v);
			});
			map1.put("host", minioConfig.getMiniourl() + "/" + bucketName);
			return map1;
		}
		catch (Exception e)
		{
			throw new Exception(ExceptionEnums.ERROR_500.getMessage());
		}
	}
 
	/**
	 * @param objectName
	 *            对象名称
	 * @param method
	 *            方法
	 * @param time
	 *            时间
	 * @param timeUnit
	 *            时间单位
	 * @Description 获取上传文件的url
	 */
	@SneakyThrows
	public String getPolicyUrl(String objectName, Method method, int time, TimeUnit timeUnit, String bucketName)
	{
		try
		{
			return minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder().method(method)
					.bucket(bucketName).object(objectName).expiry(time, timeUnit).build());
		}
		catch (Exception e)
		{
			throw new Exception(ExceptionEnums.ERROR_500.getMessage());
		}
	}
 
	/**
	 * @param file
	 *            文件
	 * @param fileName
	 *            文件名称
	 * @Description 上传文件
	 */
	public void upload(MultipartFile file, String fileName, String bucketName) throws Exception
	{
		// 使用putObject上传一个文件到存储桶中。
		InputStream inputStream = file.getInputStream();
		minioClient.putObject(PutObjectArgs.builder().bucket(bucketName).object(fileName)
				.stream(inputStream, file.getSize(), -1).contentType(file.getContentType()).build());
	}
 
	/**
	 * @param objectName
	 *            对象名称
	 * @param time
	 *            时间
	 * @param timeUnit
	 *            时间单位
	 * @Description 根据filename获取文件访问地址
	 */
	@SneakyThrows
	public String getUrl(String objectName, int time, TimeUnit timeUnit, String bucketName)
	{
		String url = null;
		try
		{
			url = minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder().method(Method.GET)
					.bucket(bucketName).object(objectName).expiry(time, timeUnit).build());
		}
		catch (Exception e)
		{
			throw new Exception(ExceptionEnums.ERROR_500.getMessage());
		}
		return url;
	}
 
	/**
	 * @Description description: 下载文件
	 */
	public void download(String bucket, String fileName, HttpServletResponse response) throws Exception
	{
		InputStream inputStream = minioClient
				.getObject(GetObjectArgs.builder().bucket(bucket).object(fileName).build());
		ServletOutputStream outputStream = response.getOutputStream();
		response.setContentType("application/octet-stream");
		response.setCharacterEncoding("utf-8");
		response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
		byte[] bytes = new byte[1024];
		int len;
		while ((len = inputStream.read(bytes)) > 0)
		{
			outputStream.write(bytes, 0, len);
		}
		outputStream.close();
	}
 
	/**
	 * @param objectFile
	 *            对象文件
	 */
	public String getFileUrl(String objectFile, String bucketName)
	{
		try
		{
 
			return minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder().method(Method.GET)
					.bucket(bucketName).object(objectFile).build());
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		return null;
	}
 
	/**
	 * 创建文件夹
	 *
	 * @param bucketName
	 * @param path
	 *            记得路径最后加一个/ 例如 bucket/folder/
	 */
	public void createFolder(String bucketName, String path) throws Exception
	{
		minioClient.putObject(PutObjectArgs.builder().bucket(bucketName).object(path)
				.stream(new ByteArrayInputStream(new byte[] {}), 0, -1).build());
	}
 
	/**
	 * 删除文件
	 *
	 * @param bucketName
	 *            库名称
	 * @param fileName
	 *            文件名称
	 * @return
	 */
	public void removeObject(String bucketName, String fileName) throws Exception
	{
		minioClient.removeObject(RemoveObjectArgs.builder().bucket(bucketName).object(fileName).build());
	}
 
	/**
	 * 文件夹删除
	 *
	 * @param bucketName
	 * @param fileName
	 * @throws Exception
	 */
	public void removeDirectory(String bucketName, String fileName) throws Exception
	{
		Iterable<Result<Item>> results = minioClient
				.listObjects(ListObjectsArgs.builder().bucket(bucketName).prefix(fileName).recursive(false).build());
		for (Result<Item> item : results)
		{
			minioClient.removeObject(
					RemoveObjectArgs.builder().bucket(bucketName).object(item.get().objectName()).build());
		}
	}
 
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值