package com.fdkankan.fyun.s3.config;

import com.amazonaws.ClientConfiguration;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.fdkankan.fyun.config.FYunFileConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

@Component
@ConditionalOnProperty(name = "fyun.type",havingValue = "aws")
public class S3Config {

    @Autowired
    private FYunFileConfig fYunFileConfig;

    /**
     * 配置多实例,且使用时候要手动shutdown,否则会造成内存溢出
     * @return
     */
    @Bean
    public AmazonS3 amazonS3(){
        BasicAWSCredentials awsCreds = new BasicAWSCredentials(fYunFileConfig.getKey(), fYunFileConfig.getSecret());
        ClientConfiguration clientConfiguration = new ClientConfiguration();
        clientConfiguration.setMaxErrorRetry(4);
        clientConfiguration.setMaxConnections(100);
        return AmazonS3ClientBuilder.standard()
                .withCredentials(new AWSStaticCredentialsProvider(awsCreds))
                .withClientConfiguration(clientConfiguration)
                .withRegion(fYunFileConfig.getRegion()).build();
    }
}
