OSSClientUtil.java 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. package com.izouma.nineth.utils;
  2. import com.aliyun.oss.OSSClient;
  3. import com.aliyun.oss.model.OSSObject;
  4. import com.fasterxml.jackson.databind.ObjectMapper;
  5. import com.fasterxml.jackson.databind.type.TypeFactory;
  6. import com.izouma.nineth.config.AliyunProperties;
  7. import java.io.IOException;
  8. import java.io.InputStream;
  9. import java.util.List;
  10. public class OSSClientUtil {
  11. /**
  12. * 通过阿里云OSSClient客户端读取指定objectKey的文件流,利用Jackson将文件流反序列化成List<T>类型的数据模型并返回。
  13. *
  14. * @param properties 用于配置阿里云OSS客户端的属性对象。
  15. * @param objectKey 阿里云OSS存储桶中的文件对象的唯一标识符。
  16. * @param clazz 要反序列化的目标类型。
  17. * @return 返回反序列化后的List<T>类型数据模型。
  18. * @throws IOException 当出现IO异常时,抛出IOException。
  19. */
  20. public static <T> List<T> getDataModel(AliyunProperties properties, String objectKey, Class<T> clazz) throws IOException {
  21. // 从阿里云OSS客户端配置对象中获取必要的参数
  22. String endpoint = properties.getOssEndPoint();
  23. String accessKeyId = properties.getAccessKeyId();
  24. String accessKeySecret = properties.getAccessKeySecret();
  25. String bucketName = properties.getOssBucketName();
  26. // 创建OSS客户端
  27. OSSClient client = new OSSClient(endpoint, accessKeyId, accessKeySecret);
  28. List<T> list;
  29. // 获取指定文件对象的OSSObject对象
  30. OSSObject ossObject = client.getObject(bucketName, objectKey);
  31. // 创建Jackson的ObjectMapper对象用于反序列化操作
  32. ObjectMapper objectMapper = new ObjectMapper();
  33. // 将OSSObject对象中的文件流反序列化成List<T>类型的数据模型
  34. try (InputStream inputStream = ossObject.getObjectContent()) {
  35. list = objectMapper.readValue(inputStream, TypeFactory.defaultInstance().constructCollectionType(List.class, clazz));
  36. } finally {
  37. // 关闭OSS客户端
  38. client.shutdown();
  39. }
  40. return list;
  41. }
  42. }