TypechoJoeTheme

Toasobi的博客

Oss服务---顺眼的整合

本文最后更新于2023年08月30日,已超过385天没有更新。如果文章内容或图片资源失效,请留言反馈,我会及时处理,谢谢!

在做Oss业务中,发现项目中Oss第三方整合的代码结构和方式比较顺眼,解耦的比较清楚,所以记录一下

  • 注:本博客以oss文件拷贝举例,其中涉及的业务代码没有任何意义,代码是按执行顺序记录

代码结构:

ConstantPropertiesUtils.java (oss配置类)
@Configuration
public class ConstantPropertiesUtils implements InitializingBean {

    @Value("${aliyun.oss.file.endpoint}")
    private String endpoint;

    @Value("${aliyun.oss.file.accessKeyId}")
    private String accessKeyId;

    @Value("${aliyun.oss.file.accessKeySecret}")
    private String accessKeySecret;

    @Value("${aliyun.oss.file.bucketName}")
    private String bucketName;

    @Value("${aliyun.oss.file.urlPrefix}")
    private String urlPrefix;

    @Value("${spring.profiles.active}")
    private String springProfilesActive;

    /**
     * Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
     * */
    public static String END_POINT;

    /**
     * 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
     * */
    public static String ACCESS_KEY_ID;
    public static String ACCESS_KEY_SECRET;

    /**
     * 填写Bucket名称
     * */
    public static String BUCKET_NAME;

    /**
     * OSS结果响应的全文件路径前缀
     * */
    public static String URL_PREFIX;

    /**
     * 环境模式
     * dev/test/product
     * */
    public static String SPRING_PROFILE_ACTIVE;

    @Override
    public void afterPropertiesSet() {
        END_POINT = endpoint;
        ACCESS_KEY_ID = accessKeyId;
        ACCESS_KEY_SECRET = accessKeySecret;
        BUCKET_NAME = bucketName;
        URL_PREFIX = urlPrefix;
        SPRING_PROFILE_ACTIVE = springProfilesActive;
    }

    /**
     * 创建OSS客户端Bean
     *
     * @return*/
    @Bean
    public OSS getOSSClient() {
        return new OSSClientBuilder().build(END_POINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
    }
}
RecipeImgCopyUtil (业务逻辑/调用oss)
/**
 * @author zengxuanwen
 * @date 2023/8/24 10:09
 * @description 菜谱图片拷贝工具
 */
public class RecipeImgCopyUtil {


    public static void recipeImgCopy(AddRecipeRespDto addRecipeRespDto, RecipeCopyRespDto dto,
                                     AddRecipeReqDto recipe, OssFileCopyService ossFileCopyService, RecipeService recipeService){
        /**
         * 1. 获取被复制菜谱和复制后菜谱的信息,拼接出新的图片url地址
         */
        //获取复制和被复制菜谱id
        Long afterId = addRecipeRespDto.getId();


        //获取菜谱的设备类型(取第一个)
        List<String> deviceModels = dto.getRecipe().getDeviceModels();
        String deviceModel = deviceModels.get(0);

        //获取复制菜谱的language
        String changedLanguage = recipe.getLanguage();

        //获取被复制菜谱的recipePic
        String recipePic = dto.getRecipe().getRecipePic();

        String fileName = recipePic.substring(recipePic.lastIndexOf("/") + 1); // 1514_1672819324165.png

        // 使用substring方法,传入索引位置,截取字符串,得到后缀名.png
        String suffix = fileName.substring(fileName.lastIndexOf("."));

        //当前时间戳
        String picTimestampSuffix = "_" + System.currentTimeMillis();

        //目标文件路径模板
        String template = "%s/v1/recipe/%s/%s/%s";

        // 使用substring方法,传入起始索引位置,截取字符串,得到新的字符串
        String sourceUrl = recipePic.substring(ConstantPropertiesUtils.URL_PREFIX.length() + 1);
        // 使用replace方法,传入旧值和新值,替换字符串中的内容,得到新的字符串
        String targetUrl = String.format(template,ConstantPropertiesUtils.SPRING_PROFILE_ACTIVE,deviceModel,changedLanguage,(afterId + picTimestampSuffix + suffix));


        /**
         * 2.使用oss工具类拷贝出新的图片
         */
        RecipeImageCopyReqDto recipeImageCopyReqDto = new RecipeImageCopyReqDto();
        recipeImageCopyReqDto.setSourceObjectName(sourceUrl);
        recipeImageCopyReqDto.setTargetName(targetUrl);
        Result result = ossFileCopyService.recipeImageCopy(recipeImageCopyReqDto);
        if(result.getCode() != 0){
            throw ApiException.error(result);
        }

        /**
         * 3.将新的图片路径通过id更新到复制菜谱
         */
        UpdateRecipeReqDto updateRecipeReqDto = new UpdateRecipeReqDto();
        updateRecipeReqDto.setId(afterId);
        updateRecipeReqDto.setRecipePic(ConstantPropertiesUtils.URL_PREFIX + "/" + targetUrl);
        recipeService.updateRecipe(updateRecipeReqDto);

    }
}
OssFileCopyService
public interface OssFileCopyService {
    Result recipeImageCopy(RecipeImageCopyReqDto reqDto);
}
OssFileCopyServiceImpl
@Service
@Slf4j
public class OssFileCopyServiceImpl implements OssFileCopyService {

    private final OssFileCopyUtil ossFileCopyUtil;

    public OssFileCopyServiceImpl(OssFileCopyUtil ossFileCopyUtil) {
        this.ossFileCopyUtil = ossFileCopyUtil;
    }


    @Override
    public Result recipeImageCopy(RecipeImageCopyReqDto reqDto) {
        return ossFileCopyUtil.OssRecipeImageCopy(reqDto.getSourceObjectName(), reqDto.getTargetName());
    }
}
OssFileCopyUtil
/**
 * @author zengxuanwen
 * @date 2023/8/23 15:40
 * @description 文件拷贝工具
 */
@Slf4j
@Component
public class OssFileCopyUtil {

    @Resource
    private OSS ossClient;

    public Result OssRecipeImageCopy(String sourceObjectName, String targetName) {
        log.info("------OSS文件拷贝开始--------");


        // 指定源文件所在的存储空间和文件名。
        String sourceBucketName = ConstantPropertiesUtils.BUCKET_NAME;

        // 指定目标文件所在的存储空间和文件名。
        String destinationBucketName = ConstantPropertiesUtils.BUCKET_NAME;


        try {
            // 拷贝文件。
            ossClient.copyObject(sourceBucketName, sourceObjectName, destinationBucketName, targetName);
            // 打印拷贝结果。
            log.info("拷贝成功,新的文件名为:" + targetName);
        } catch (OSSException e) {
            // 处理OSS服务端异常。
            log.error("拷贝失败,错误码:" + e.getErrorCode() + ",错误信息:" + e.getErrorMessage());
            return Result.error(e);
        } catch (ClientException e) {
            // 处理客户端异常。
            log.error("拷贝失败,错误信息:" + e.getMessage());
            return Result.error(e);
        }
        return Result.success();
    }
}
朗读
赞(0)
评论 (0)