使用minio给存储的对象添加过期时间

本文介绍了如何在Linux环境下使用Docker部署的Minio服务,配置定时清理策略,并通过Java实现文件上传。重点展示了配置类中设置桶生命周期规则和上传工具类的实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在一些场景中,储存的对象需要定时清理保证留出足够的磁盘空间,如果时linux的本地文件,需要采取定时任务清理,但是minio提供了这样的能力

环境

软件版本
docker24.0.4
minioRELEASE.2023-10-24T05-18-28Z (commit-id=97cc12fdc539361cf175ffc2f00480eec0836d82)

客户端(浏览器)

打开对应的桶
在这里插入图片描述
在这里添加

通过代码(这里以java为例)

配置类

@Configuration
public class MinioConfig {

    @Value("${minio.endpoint}")
    private String endpoint;

    @Value("${minio.accessKey}")
    private String accessKey;

    @Value("${minio.secretKey}")
    private String secretKey;

    @Bean
    public MinioClient minioClient() {
        MinioClient client = MinioClient.builder()
                .endpoint(endpoint)
                .credentials(accessKey, secretKey)
                .build();
        try {
            client.setBucketLifecycle(
                    SetBucketLifecycleArgs
                            .builder()
                            .config(new LifecycleConfiguration(
                                    List.of(
                                            new LifecycleRule(Status.ENABLED,
                                                    null,
                                                    new Expiration((ResponseDate) null, 180, null),
                                                    new RuleFilter("/"),
                                                    "myDeleteRule",
                                                    null,
                                                    null,
                                                    null)
                                    )
                            ))
                            .bucket("vits")
                            .build()
            );
        } catch (ErrorResponseException | InsufficientDataException | InternalException | InvalidKeyException |
                 InvalidResponseException | IOException | NoSuchAlgorithmException | ServerException |
                 XmlParserException e) {
            throw new RuntimeException(e);
        }
        return client;
    }
}

上传工具类

@Slf4j
public class MinioUtils {

    public static String uploadFile(MinioClient minioClient, InputStream inputStream, String bucket, String filename) {
        try {
            boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket("public").build());
            if (!found) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket("public").build());
            }

            ObjectWriteResponse response = minioClient.putObject(
                    PutObjectArgs
                            .builder()
                            .bucket(bucket)
                            .object(filename)
                            .stream(inputStream, inputStream.available(), -1)
                            .contentType(InferStatusConstant.WAV_CONTENT_TYPE)
                            .build()
            );

            String url = minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder()
                            .bucket(bucket)
                            .expiry(7 * 24 * 60 * 60)
                            .object(filename)
                            .method(Method.GET)
                            .build());
            log.info("分享地址:" + url);
            return url;
        } catch (ErrorResponseException | InsufficientDataException | InternalException | InvalidKeyException |
                 InvalidResponseException | IOException | NoSuchAlgorithmException | ServerException |
                 XmlParserException e) {
            throw new RuntimeException(e);
        }
    }
}

测试类

@Test
public void uploadFileToMinio() {
    try (FileInputStream stream = new FileInputStream("/path/to/file")) {
        String url = MinioUtils.uploadFile(minioClient, stream, "public", "/path/to/file");
        System.out.println(url);
    } catch (Exception e) {

    }
}
MinIO是一个开源的对象存储服务,可以与Spring Boot集成来作为应用程序的数据存储。如果你想要设置文件Spring Boot应用中存储14天后自动过期,通常不会直接在MinIO客户端库中设置这种过期策略,因为这是服务器端的行为,而非客户端控制。不过,你可以通过配置两个步骤来实现: 1. **在MinIO存储桶上设置生命周期规则**: - 登录到MinIO管理控制台或使用MinIO Java SDK,在存储桶级别创建一个生命周期规则。这允许你在文件上传后设定特定条件下的自删除时间。例如,你可以创建一个规则,当对象未访问超过14天时,将自动删除。 ```java // 示例Java代码 (假设已经添加MinIO的依赖) AmazonS3 s3Client = AmazonS3ClientBuilder.standard().build(); PutLifecycleConfigurationRequest request = new PutLifecycleConfigurationRequest(bucketName); PutObjectMetadata metadata = new PutObjectMetadata(); metadata.setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 24 * 14)); // 14天后过期 List<LifecycleRule> rules = new ArrayList<>(); rules.add(new LifecycleRule() .withId("rule-id") .withFilter(new AndOperator( new TagFilter(Arrays.asList("key", "value")) // 根据tag设置过期 )) .withStatus(LifecycleRule.Status.ENABLED) .withExpiration(metadata.getExpiration())); request.withRules(rules); s3Client.putLifecycleConfiguration(request); ``` 2. **在Spring Boot中保存文件添加过期标签**: - 如果需要,可以在文件上传至MinIO之前,为其添加过期时间相关的元数据标签,以便在生命周期规则中引用。 记得检查MinIO官方文档以获取最新版本的SDK使用说明,并根据实际需求调整上述示例。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值