springboot 天翼云融合版集成

1.引入pom

		<!-- 引入天翼云sts服务  -->
        <dependency>
		    <groupId>com.amazonaws</groupId>
		    <artifactId>aws-java-sdk-s3</artifactId>
		    <version>1.11.336</version>
		</dependency>
		<dependency>
		    <groupId>com.amazonaws</groupId>
		    <artifactId>aws-java-sdk-sts</artifactId>
		    <version>1.11.336</version>
		</dependency>

2.yml配置

在这里插入图片描述

3.天翼云基础配置

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * 天翼云基础配置
 * @author: wanjun
 */
@Component
public class CtyunConfig
{

    /**
     * OSS身份id
     */
    @Value("${ctyun-oos.accessKey}")
    private String accessKey;
    
    /**
     * 身份密钥
     */
    @Value("${ctyun-oos.secretKey}")
    private String secretKey;
    
    /**
     * 服务器地址
     */
    @Value("${ctyun-oos.endpoint}")
    private String endpoint;
    
    /**
     * 文件bucketName
     */
    @Value("${ctyun-oos.bucketName}")
    private String bucketName;
    
    /**
     * 文件地址前缀
     */
    @Value("${ctyun-oos.domainApp}")
    private String domainApp;
    
    /**
     * sts 指定角色的ARN。格式:arn:aws:iam:::role/<your-role-arn> 。
     */
    @Value("${ctyun-oos.roleArn}")
    private String roleArn;

	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 getEndpoint()
	{
		return endpoint;
	}

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

	public String getBucketName()
	{
		return bucketName;
	}

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

	public String getDomainApp()
	{
		return domainApp;
	}

	public void setDomainApp(String domainApp)
	{
		this.domainApp = domainApp;
	}

	public String getRoleArn()
	{
		return roleArn;
	}

	public void setRoleArn(String roleArn)
	{
		this.roleArn = roleArn;
	} 
}

4.天翼云存储工具类

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.amazonaws.AmazonServiceException;
import com.amazonaws.ClientConfiguration;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.client.builder.AwsClientBuilder.EndpointConfiguration;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.CannedAccessControlList;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.amazonaws.services.s3.model.PutObjectResult;
import com.amazonaws.services.s3.transfer.TransferManager;
import com.amazonaws.services.s3.transfer.TransferManagerBuilder;
import com.amazonaws.services.s3.transfer.Upload;
import com.amazonaws.services.s3.transfer.model.UploadResult;
import com.booway.cloud.model.OssFileModel;
import com.booway.course.file.config.CtyunConfig;

/**
 * 天翼云存储工具类
 * @author: wanjun
 */

@Component
public class CtyunUtil
{

	private static final Logger log = LoggerFactory.getLogger(CtyunUtil.class);
	
	public static final String POINT = ".";

	public static final String SLASH = "/";

	@Autowired
	private CtyunConfig ctyunConfig;

	/**
	 * @Description: 初始化天翼云存储服务
	 * @return: AmazonS3
	 */
	private AmazonS3 getClient()
	{

		BasicAWSCredentials credentials = new BasicAWSCredentials(ctyunConfig.getAccessKey(), ctyunConfig.getSecretKey());
		ClientConfiguration clientConfiguration = new ClientConfiguration();
		// 设置client的最大HTTP连接数
		clientConfiguration.setMaxConnections(50);
		// 设置Socket层超时时间,单位毫秒
		clientConfiguration.setSocketTimeout(50 * 1000);
		// 设置建立连接的超时时间,单位毫秒
		clientConfiguration.setConnectionTimeout(50 * 1000);
		EndpointConfiguration endpointConfiguration = new EndpointConfiguration(ctyunConfig.getEndpoint(), Regions.DEFAULT_REGION.getName());
		AmazonS3 oosClient = AmazonS3ClientBuilder.standard()
				// 客户端设置
				.withClientConfiguration(clientConfiguration)
				// 凭证设置
				.withCredentials(new AWSStaticCredentialsProvider(credentials))
				// endpoint设置
				.withEndpointConfiguration(endpointConfiguration).build();
		return oosClient;
	}
/**
	 * 创建天翼云 OOS 临时token
	 * @throws Exception 
	 */
	public Credentials createStsToken(String bucketName) throws Exception
	{
		if(!doesBucketExist(bucketName)) {
			throw new Exception("bucket不存在");
		}
		AmazonS3 oosClient = getClient();
		try
		{
			// 允许操作默认桶中的所有文件,可以修改此处来保证操作的文件
			String POLICY = "{\"Version\":\"2012-10-17\"," + "\"Statement\":" + "{\"Effect\":\"Allow\"," + "\"Action\":[\"s3:*\"],"
					+ "\"Resource\":[\"arn:aws:s3:::" + bucketName + "\",\"arn:aws:s3:::" + bucketName + "/*\"]" + "}}";
			AWSSecurityTokenService stsClient = buildSTSClient();
			AssumeRoleRequest assumeRoleRequest = new AssumeRoleRequest();
			assumeRoleRequest.setRoleArn(ctyunConfig.getRoleArn());
			assumeRoleRequest.setPolicy(POLICY);
			assumeRoleRequest.setRoleSessionName("session-name");
			assumeRoleRequest.setDurationSeconds(43200);
			AssumeRoleResult assumeRoleRes = stsClient.assumeRole(assumeRoleRequest);
			Credentials stsCredentials = assumeRoleRes.getCredentials();
			return stsCredentials;
		}
		catch (Exception e)
		{
			log.error(e.getMessage());
			e.printStackTrace();
		}
		finally
		{
			if (oosClient != null)
			{
				oosClient.shutdown();
			}
		}
		return null;
	}

	/**
	 * @Description: 初始化STS服务
	 * @return: AWSSecurityTokenService
	 */
	private AWSSecurityTokenService buildSTSClient()
	{
		BasicAWSCredentials credentials = new BasicAWSCredentials(ctyunConfig.getAccessKey(), ctyunConfig.getSecretKey());
		AwsClientBuilder.EndpointConfiguration endpointConfiguration = new AwsClientBuilder.EndpointConfiguration(ctyunConfig.getEndpoint(), Regions.DEFAULT_REGION.getName());
		return AWSSecurityTokenServiceClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(credentials)).withEndpointConfiguration(endpointConfiguration).build();
	}
	
	/**
	 * @Description: 获取天翼云临时下载地址
	 * @param bucketName 桶名称
	 * @param objectName 操作对象(例如:2022/05/30/linux.txt)
	 * @param mins 失效时长:分钟
	 * @return: String 临时下载地址
	 * @throws Exception 
	 */
	public String generatePresignedUrl(String bucketName, String objectName) throws Exception
	{
		if(!doesBucketExist(bucketName)) {
			throw new Exception("bucket不存在");
		}
		if(!doesObjectExist(bucketName, objectName)) {
			throw new Exception("文件不存在");
		}
		AmazonS3 oosClient = getClient();
		try
		{
			LocalDateTime expirationDateTime = LocalDateTime.now().plusSeconds(60 * 60);
			Date expiration = Date.from(expirationDateTime.atZone(ZoneId.systemDefault()).toInstant());
			GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(bucketName, objectName).withMethod(HttpMethod.GET).withExpiration(expiration);
			URL url = oosClient.generatePresignedUrl(generatePresignedUrlRequest);
			return url.toString();
		}
		catch (Exception e)
		{
			log.error(e.getMessage());
			e.printStackTrace();
		}
		finally
		{
			if (oosClient != null)
			{
				oosClient.shutdown();
			}
		}
		return null;
	}

	/**
	 * @Description: 判断bucketName桶是否存在
	 * @param bucketName
	 * @return: Boolean
	 */
	public Boolean doesBucketExist(String bucketName)
	{
		AmazonS3 oosClient = getClient();
		try
		{
			return oosClient.doesBucketExistV2(bucketName);
		}
		catch (Exception e)
		{
			log.error(e.getMessage());
			e.printStackTrace();
		}
		finally
		{
			if (oosClient != null)
			{
				oosClient.shutdown();
			}
		}
		return false;
	}
	
	/**
	 * @Description: 判断bucketName存储桶下文件是否存在
	 * @param bucketName
	 * @return: Boolean
	 */
	public Boolean doesObjectExist(String bucketName, String objectName)
	{
		AmazonS3 oosClient = getClient();
		try
		{
			return oosClient.doesObjectExist(bucketName, objectName);
		}
		catch (Exception e)
		{
			log.error(e.getMessage());
			e.printStackTrace();
		}
		finally
		{
			if (oosClient != null)
			{
				oosClient.shutdown();
			}
		}
		return false;
	}

	/**
	 * @Description: 文件上传
	 * @param fileName 文件名
	 * @param fileIns 文件流
	 * @param storagePath  存储路径
	 * @return: OssFileModel  返回封装对象
	 */
	public OssFileModel uploadFile(String fileName, InputStream fileIns, String storagePath)
	{
		AmazonS3 oosClient = getClient();
		UploadResult partUploadFileResult = null;
		PutObjectResult putObjectResult = null;
		try
		{
			String bucketName = ctyunConfig.getBucketName();
			log.info("bucketName={}",bucketName);
			if (!oosClient.doesBucketExistV2(bucketName))
			{
				oosClient.createBucket(bucketName);
			}
			// 文件大小
			int fileSize = fileIns.available();
			String contentType = Util.getContentType(fileName);
			boolean publicRead = contentType.startsWith("image") || contentType.startsWith("application") || contentType.startsWith("text") || contentType.startsWith("ts") || contentType.startsWith("m3u8");

			// 大于1GB的文件分片上传
			if (fileSize > 104857600)
			{
				partUploadFileResult = partUploadFile(fileIns, storagePath, publicRead);
			}
			else
			{
				PutObjectRequest req = new PutObjectRequest(bucketName, storagePath, fileIns, null);
				if (publicRead)
				{
					req.setCannedAcl(CannedAccessControlList.PublicRead);
				}
				putObjectResult = oosClient.putObject(req);
			}
			if (partUploadFileResult != null || putObjectResult != null)
			{
				String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
				String eTag = partUploadFileResult != null ? partUploadFileResult.getETag() : putObjectResult.getETag();
				OssFileModel ossFileModel = OssFileModel.builder().fileName(fileName).fileSize(fileSize).cloudAbsolutePath(storagePath).cloudPath(ctyunConfig.getDomainApp() + SLASH + storagePath).fileSuffix(suffix).fileBucket(bucketName).md5(eTag).build();
				log.info("上传成功===>>>返回对象={}",com.alibaba.fastjson.JSONObject.toJSONString(ossFileModel));
				return ossFileModel;
			}
		}
		catch (AmazonServiceException e)
		{
			e.printStackTrace();
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			if (oosClient != null)
			{
				oosClient.shutdown();
			}
			if (fileIns != null)
			{
				IOUtils.closeQuietly(fileIns);
			}
		}
		return null;
	}

	/**
	 * @Description: 大文件上传
	 * @param fileIns 文件流
	 * @param storagePath 存储路径
	 * @param publicRead 文件权限
	 * @return: UploadResult
	 */
	private UploadResult partUploadFile(InputStream fileIns, String storagePath, boolean publicRead)
	{
		AmazonS3 oosClient = getClient();
		try
		{
			TransferManager tm = TransferManagerBuilder.standard().withS3Client(oosClient).build();
			// TransferManager 采用异步方式进行处理,因此该调用会立即返回。
			PutObjectRequest request = new PutObjectRequest(ctyunConfig.getBucketName(), storagePath, fileIns, null);
			if (publicRead)
			{
				request.withCannedAcl(CannedAccessControlList.PublicRead);
			}
			Upload upload = tm.upload(request);
			// 等待上传全部完成。
			UploadResult result = upload.waitForUploadResult();
			return result;
		}
		catch (AmazonServiceException e)
		{
			e.printStackTrace();
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			if (oosClient != null)
			{
				oosClient.shutdown();
			}
			if (fileIns != null)
			{
				IOUtils.closeQuietly(fileIns);
			}
		}
		return null;
	}

5.补充 OssFileModel

import lombok.Builder;
import lombok.Data;

/**
 * oss上传接收model
 * @author: wanjun
 */

@Data
@Builder
public class OssFileModel
{

    /**
     * 文件名
     */
    private String fileName;

    /**
     * 文件大小
     */
    private long fileSize;
    /**
     * 文件的绝对路径
     */
    private String cloudAbsolutePath;

    /**
     * 文件的web访问地址
     */
    private String cloudPath;

    /**
     * 文件后缀
     */
    private String fileSuffix;

    /**
     * 存储的bucket
     */
    private String fileBucket;

    /**
     * 文件MD5
     */
    private String md5;

    public OssFileModel()
    {
        
    }

    public OssFileModel(String fileName, long fileSize, String cloudAbsolutePath, String cloudPath, String fileSuffix,
            String fileBucket, String MD5)
    {
        super();
        this.fileName = fileName;
        this.fileSize = fileSize;
        this.cloudAbsolutePath = cloudAbsolutePath;
        this.cloudPath = cloudPath;
        this.fileSuffix = fileSuffix;
        this.fileBucket = fileBucket;
        this.md5 = MD5;
    }

}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值