java获取服务器配置文件的值

获取服务器配置文件的值

    @Value("${bpm.minio.bucketName:}")
    private String minioBarrel;

在这里插入图片描述

获取nacos 配置文件的值

  • minio配置类
package com.guodi.bpm.common.minio;

import org.springframework.boot.context.properties.ConfigurationProperties;


/**
 * minio配置
 *
 * @author lwh
 * @since 2023-03-21
 */
@ConfigurationProperties(prefix = "bpm.minio")
public class MinioProperties {

    /**
     * MinIO地址
     */
    private String endpoint;

    /**
     * 访问的key
     */
    private String accessKey;

    /**
     * 访问的秘钥
     */
    private String secretKey;

    /**
     * 存储桶名称
     */
    private String bucketName;

    public String getEndpoint() {
        return endpoint;
    }

    public void setEndpoint(String endpoint) {
        this.endpoint = endpoint;
    }

    public String getAccessKey() {
        return accessKey;
    }

    public void setAccessKey(String accessKey) {
        this.accessKey = accessKey;
    }

    public String getSecretKey() {
        return secretKey;
    }

    public void setSecretKey(String secretKey) {
        this.secretKey = secretKey;
    }

    public String getBucketName() {
        return bucketName;
    }

    public void setBucketName(String bucketName) {
        this.bucketName = bucketName;
    }
}

  • minio实现类
package com.guodi.bpm.service.impl;

import com.guodi.bpm.common.auth.secure.utils.FileUtil;
import com.guodi.bpm.common.auth.secure.utils.Func;
import com.guodi.bpm.common.auth.secure.utils.StringPool;
import com.guodi.bpm.common.auth.secure.utils.StringUtil;
import com.guodi.bpm.common.minio.MinioException;
import com.guodi.bpm.common.minio.MinioProperties;
import com.guodi.bpm.common.minio.model.MinioFile;
import com.guodi.bpm.common.minio.model.StorageObject;
import com.guodi.bpm.service.IFileService;
import io.minio.*;
import io.minio.messages.Item;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.util.CollectionUtils;

import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.sql.Date;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Optional;

/**
 * minio文件获取存储实现类
 *
 * @author 梁伟浩
 * @date 2023/9/13 11:06
 * @study 星期三
 */
@EnableConfigurationProperties({MinioProperties.class})
public class MinIOFileServiceImpl implements IFileService {


    private static final Logger LOGGER = LoggerFactory.getLogger(MinIOFileServiceImpl.class);

    public static final String DEFAULT_ENCODED = "UTF-8";

    private final String bucketName;

    private final MinioClient minioClient;

    private final String endpoint;


    public MinIOFileServiceImpl(MinioProperties minioProperties) {
        this.minioClient = this.getMinioClient(minioProperties);
        this.bucketName = minioProperties.getBucketName();
        this.endpoint = minioProperties.getEndpoint();
    }


    public MinioClient getMinioClient(MinioProperties minioProperties) {
        String endpoint = minioProperties.getEndpoint();
        String accesskey = minioProperties.getAccessKey();
        String secretkey = minioProperties.getSecretKey();
        String bucketName = minioProperties.getBucketName();
        if (endpoint == null || "".equals(endpoint)) {
            throw new MinioException("Minio的URL未在application.yml配置!");
        }
        if (accesskey == null || "".equals(accesskey)) {
            throw new MinioException("Minio用户名未在application.yml配置!");
        }
        if (secretkey == null || "".equals(secretkey)) {
            throw new MinioException("Minio密码未在application.yml配置!");
        }
        if ((bucketName == null || "".equals(bucketName))) {
            throw new MinioException("存储桶名称未在application.yml配置!");
        }
        MinioClient minioClient =
                MinioClient.builder()
                        .endpoint(endpoint)
                        .credentials(accesskey, secretkey)
                        .build();

        makeBucket(minioClient, bucketName);
        return minioClient;
    }


    /**
     * 创建minio存储桶
     *
     * @param minioClient minio客户端
     * @param bucketName  桶名称
     */
    private void makeBucket(MinioClient minioClient, String bucketName) {
        try {
            //创建一个MinIO的Java客户端
            boolean isExist = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            if (!isExist) {
                //创建存储桶
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
                //设置桶策略
                String policyJson =
                        "{\n" +
                                "     \"Statement\": [\n" +
                                "         {\n" +
                                "             \"Action\": [\n" +
                                "                 \"s3:GetBucketLocation\",\n" +
                                "                 \"s3:ListBucket\"\n" +
                                "             ],\n" +
                                "             \"Effect\": \"Allow\",\n" +
                                "             \"Principal\": \"*\",\n" +
                                "             \"Resource\": \"arn:aws:s3:::" + bucketName + "\"\n" +
                                "         },\n" +
                                "         {\n" +
                                "             \"Action\": [\n" +
                                "                 \"s3:GetObject\",\n" +
                                "                 \"s3:PutObject\"\n" +
                                "             ],\n" +
                                "             \"Effect\": \"Allow\",\n" +
                                "             \"Principal\": \"*\",\n" +
                                "             \"Resource\": \"arn:aws:s3:::" + bucketName + "/*\"\n" +
                                "         }\n" +
                                "     ],\n" +
                                "     \"Version\": \"2012-10-17\"\n" +
                                " }";
                minioClient.setBucketPolicy(
                        SetBucketPolicyArgs.builder().bucket(bucketName).config(policyJson).build());
            }
        } catch (Exception e) {
            throw new MinioException("创建minio存储桶异常", e);
        }
    }

    /**
     * 添加 存储对象
     *
     * @param objectName  存储对象名称
     * @param inputStream 输入流
     * @return url
     */
    @Override
    public String putObject(String objectName, InputStream inputStream) {
        if ((objectName == null || "".equals(objectName))) {
            throw new MinioException("存储对象名称objectName不能为空!");
        }
        try {
            minioClient.putObject(
                    PutObjectArgs.builder().bucket(bucketName).object(objectName).stream(
                            inputStream, -1, 10485760)
                            .build());
            LOGGER.info("文件上传成功!");
            return URLDecoder.decode(this.getObjectUrl(objectName), "utf-8");
        } catch (Exception e) {
            throw new MinioException(e.getMessage(), e);
        }
    }

    /**
     * 获取 存储对象
     *
     * @param objectName 存储对象名称
     * @return inputStream
     */
    @Override
    public InputStream getObject(String objectName) {
        InputStream inputStream = null;
        try {
            inputStream = minioClient.getObject(
                    GetObjectArgs.builder()
                            .bucket(bucketName)
                            .object(objectName)
                            .build());
        } catch (Exception e) {
            throw new MinioException("minio获取储存对象路径不存在!", e.getCause());
        }
        return inputStream;
    }


    /**
     * @描述: 获取文件大小
     * @入参: fileUrl:文件访问全路径
     * @出参: 文件大小
     * @作者: 肖俊杰
     * @日期: 2021/11/4 15:36
     **/
    @Override
    public Long getFileSize(String fileUrl) {
        Long fileSize = 0L;
        try {
            if (fileUrl.indexOf(bucketName) != -1) {
                fileUrl = StringUtil.sub(fileUrl,
                        fileUrl.indexOf(bucketName) + bucketName.length(), -1);
            }
            MinioFile minioFile = this.getMinioFile(fileUrl);
            if (minioFile != null) {
                fileSize = minioFile.getLength();
            }
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("下载发生错误: {}!", e.getMessage());
            return fileSize;
        }
        return fileSize;
    }

    /**
     * 获取 存储对象
     *
     * @param objectName   存储对象名称
     * @param outputStream 输出流
     */
    @Override
    public void getObject(String objectName, OutputStream outputStream) {
        InputStream is = getObject(objectName);
        Optional.ofNullable(is).ifPresent(inputStream -> {
            try {
                byte[] buffer = new byte[2048];
                int len = 0;
                while ((len = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, len);
                }
                outputStream.flush();
            } catch (Exception e) {
                throw new MinioException(e.getMessage(), e);
            }
        });
    }

    /**
     * 获取对象列表
     *
     * @param objectPrefix 对象前缀
     * @return 对象列表
     * @author 陈国勇
     * @since 2023--4-18
     */
    @Override
    public List<StorageObject> listObjects(String objectPrefix) throws MinioException {
        List<StorageObject> storageObjects = new ArrayList<>();
        try {
            Iterable<Result<Item>> objects = minioClient.listObjects(
                    ListObjectsArgs.builder()
                            .bucket(bucketName)
                            .prefix(objectPrefix)
                            .recursive(true)
                            .build()
            );
            for (Result<Item> itemResult : objects) {
                Item item = itemResult.get();
                StorageObject storageObject = new StorageObject();
                storageObject.setBucketName(bucketName);
                storageObject.setObjectName(item.objectName());
                storageObjects.add(storageObject);
            }
        } catch (Exception e) {
            throw new MinioException(e.getMessage(), e);
        }
        return storageObjects;
    }

    /**
     * 根据存储对象名称 删除 存储对象
     *
     * @param objectName 存储对象名称
     */
    @Override
    public void removeObject(String objectName) {
        try {
            minioClient.removeObject(RemoveObjectArgs.builder().bucket(bucketName).object(objectName).build());
        } catch (Exception e) {
            throw new MinioException(e.getMessage(), e);
        }
    }

    /**
     * 根据文件访问全路径删除 存储对象
     *
     * @param fileUrl :文件访问全路径地址
     */
    @Override
    public void removeByFileUrl(String fileUrl) {
        try {
            String downloadUrl = fileUrl.substring(fileUrl.indexOf(bucketName) + bucketName.length());
            minioClient.removeObject(RemoveObjectArgs.builder().bucket(bucketName).object(downloadUrl).build());
        } catch (Exception e) {
            throw new MinioException(e.getMessage(), e);
        }
    }

    /**
     * 批量删除 存储对象
     *
     * @param objectNames 存储对象名称集合
     */
    @Override
    public void removeObjectBatch(Collection<String> objectNames) {
        if (!CollectionUtils.isEmpty(objectNames)) {
            objectNames.forEach(objectName -> {
                this.removeObject(objectName);
            });
        }
    }

    /**
     * 下载 存储对象
     *
     * @param objectName 存储对象名称
     * @param fileName   下载存储路径及文件名
     */
    @Override
    public void downloadObject(String objectName, String fileName) {
        try {
            minioClient.downloadObject(
                    DownloadObjectArgs.builder()
                            .bucket(bucketName)
                            .object(objectName)
                            .filename(fileName).build());
        } catch (Exception e) {
            throw new MinioException(e.getMessage(), e);
        }
    }

    /**
     * 根据存储对象名称获取Url
     *
     * @param objectName 存储对象名称
     * @return url
     */
    @Override
    public String getObjectUrl(String objectName) {
        try {
            return minioClient.getObjectUrl(bucketName, objectName);
        } catch (Exception e) {
            throw new MinioException(e.getMessage(), e);
        }
    }

    /**
     * 根据存储对象名称获取Mino文件对象
     *
     * @param objectName 存储对象名称
     * @return MinioFile
     */
    private MinioFile getMinioFile(String objectName) {
        MinioFile minoFile = new MinioFile();
        try {
            ObjectStat stat = minioClient.statObject(StatObjectArgs.builder().bucket(bucketName).object(objectName).build());
            String name = Func.isEmpty(stat.name()) ? StringUtil.sub(objectName, objectName.lastIndexOf("/") + 1
                    , objectName.length()) : StringUtil.sub(stat.name(), stat.name().lastIndexOf("/") + 1
                    , stat.name().length());
            minoFile.setName(name);
            minoFile.setLink(fileLink(stat.name()));
            minoFile.setHash(String.valueOf(stat.hashCode()));
            minoFile.setLength(stat.length());
            minoFile.setPutTime(Date.from(stat.createdTime().toInstant()));
            minoFile.setContentType(stat.contentType());
            minoFile.setSuffix(name.substring(name.lastIndexOf(".") + 1));
        } catch (Exception e) {
            LOGGER.error("读取存储对象异常", e);
            throw new MinioException("读取存储对象异常", e);
        }
        return minoFile;
    }

    @Override
    public String fileLink(String fileName) {
        return StringPool.SLASH.concat(bucketName).concat(StringPool.SLASH).concat(fileName);
    }

    /**
     * @param link
     * @描述 文件路径截取、转码以及格式化
     * <p>
     * 截取:全路径会截取为相对路径,示例:http://10.3.1.60:9000/guodi/1.png 变成 /guodi/1.png
     * 转码:中文乱码直接转成UTF-8编码
     * 格式化:文件路径中正斜杠会替换成反斜杠
     * </p>
     * @作者 肖俊杰
     * @日期 2022/1/6 9:54
     * @入参 link
     * @出参 String
     */
    @Override
    public String formatLink(String link) {
        if (StringUtil.isBlank(link)) {
            return null;
        }
        if (link.indexOf(endpoint) != -1) {
            link = StringUtil.sub(link, link.indexOf(endpoint) + endpoint
                    .length());
        }
        try {
            link = FileUtil.formatUrl(link);
            link = URLDecoder.decode(link, DEFAULT_ENCODED);
        } catch (UnsupportedEncodingException e) {
            LOGGER.error(e.getMessage());
        }
        return link;
    }
    
  /**
     * 获取储存桶名称
     * @作者 梁伟浩
     * @日期 2024/1/26 10:12
     * @study 星期五
     * @return bucketName
     */
    @Override
    public String getBucketName() {
        return bucketName;
    }
}

在这里插入图片描述

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Java中的战斗机

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值