阿里云oss中java实现

2018-07-13 09:39:00
admin
原创
1346
摘要:阿里云oss中java实现

我们项目的应用场景:

一、我需要把文件同时上传到澳洲和上海的服务器,在访问的时候根据不同的地区,获取不同的地址进行访问文件。

我写了一个异步,同时上传两个服务器,但是遇到了一个问题,如果传过来的是inputstream,因为inputstream是synchronized,不同同时访问,所有用了ByteArrayOutputStream ,但是当文件太大的时候会出现内存溢出的情况,
遇到的问题:工具类中不能获取静态的实例化对象,只能通过set方法获取,set方法不能是静态的


import com.aliyun.oss.OSSClient;
import io.sbed.common.constant.FileType;
import io.sbed.common.constant.OSSConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.*;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.UUID;

/**
 * @author shisan
 * @Description: TODO(oss上传和下载工具类)
 * @date 2017-6-23 15:07
 */
@Component
public class OSSUtils {
    private static  Logger logger= LoggerFactory.getLogger(OSSUtils.class);

    private  static OSSAsync ossAsync;
    /**
     *
     * @param fileType(文件后缀:例如:txt,pdf,)
     * @param inputStream(inputstream不能重复使用,所以需要copy一个新的输入流)
     * @return
     */
    public  static Result uploadFile(FileType fileType, InputStream inputStream) throws Exception {
        logger.info("服务器的地址是"+area);
        long begin = System.currentTimeMillis();
        String filename=getFilePahBySuffix(fileType.getValue());
        try{
            ByteArrayOutputStream baos = cloneInputStream(inputStream);
            InputStream stream1 = new ByteArrayInputStream(baos.toByteArray());
            InputStream stream2 = new ByteArrayInputStream(baos.toByteArray());
            ossAsync.uploadAoleFile(filename,stream1);
            ossAsync.uploadAuFile(filename,stream2);
        }catch (Exception e){
             e.printStackTrace();
             return Result.error(e.getMessage());
        }finally {
            inputStream.close();
        }
        return  Result.ok(filename);
    }


    /**
     * 根据key获取OSS服务器上的路径
     * @param key Bucket下的文件的路径名+文件名
     */
    public static  String getAoleOssPath(String key){
        OSSClient ossClient=null;
        try{
            ossClient = getOSSClient(OSSConstant.AOLE_ENDPOINT, OSSConstant.ACCESS_KEY_ID, OSSConstant.ACCESS_KEY_SECRET);
            Date date = new Date();
            Calendar c = Calendar.getInstance();
            c.setTime(date);
            c.add(Calendar.HOUR_OF_DAY, 1);
            date=c.getTime();
            URL url= ossClient.generatePresignedUrl(OSSConstant.AOLE_BUCKET_NAME, key,date);
            return url.toString();
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 根据key获取OSS服务器上的路径
     * @param key Bucket下的文件的路径名+文件名
     */
    public static  String  getAuOssPath(String key){
        OSSClient ossClient=null;
        try{
            ossClient = getOSSClient(OSSConstant.AOLE_AU_ENDPOINT, OSSConstant.ACCESS_KEY_ID, OSSConstant.ACCESS_KEY_SECRET);
            Date expiration = new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 24);
            URL url= ossClient.generatePresignedUrl(OSSConstant.AU_BUCKET_NAME, key,expiration);
            return url.toString();
        }catch (Exception e){
            e.getMessage();
        }
        return "";
    }

    private static String area;

    /**
     * 根据key获取OSS服务器上的路径(全局,会获取区域)
     * @param key Bucket下的文件的路径名+文件名
     */
    public static String getOSSPath(String key){
        logger.info("服务器的地址是"+area);
        if("Australia".equals(area)){
            return  getAuOssPath(key);
        }
        return  getAoleOssPath(key);
    }
    public static OSSClient getOSSClient(String endpoint,String accessKeyId,String accessKeySecret){
        return new OSSClient(endpoint, accessKeyId, accessKeySecret);
    }
    /**
     * inputstream流的复制
     * @param input
     * @return
     */
    private static ByteArrayOutputStream cloneInputStream(InputStream input) {

        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len;
            while ((len = input.read(buffer)) > -1) {
                baos.write(buffer, 0, len);
            }
            baos.flush();
            return baos;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    public static void main(String[] args) throws IOException {
//        InputStream inputStream=new FileInputStream(new File("d:/1.txt"));
//        uploadFile(FileType.TXT,inputStream);
//        System.out.println(getAuOssInputStream("224.txt")) ;
//        inputstreamtofile(inputStream,new File("d:/2.txt"));

    }

    /**
     * 测试根据inputstream生成文件
     * @param ins
     * @param file
     * @throws IOException
     */
    public static void inputstreamtofile(InputStream ins, File file) throws IOException {
        OutputStream os = new FileOutputStream(file);
        int bytesRead = 0;
        byte[] buffer = new byte[8192];
        while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
            os.write(buffer, 0, bytesRead);
        }
        os.close();
        ins.close();
    }

    /**
     * 服务器上传的文件名字
     * @param suffix
     * @return
     */
    public static String getFilePahBySuffix(String suffix){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        Date date = new Date();
        return sdf.format(date)+"/"+ UUID.randomUUID()+"."+suffix;
    }
    @Value("${area}")
    public  void setArea(String area) {
        OSSUtils.area = area;
    }
    @Autowired
    public  void setOssAsync(OSSAsync ossAsync) {
        OSSUtils.ossAsync = ossAsync;
    }


二、异步的代码实现如图所示

import com.aliyun.oss.OSSClient;
import io.sbed.common.constant.OSSConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStream;

@Component
public class OSSAsync {
    private Logger logger=LoggerFactory.getLogger(OSSAsync.class);
    /**
     * 国内上传
     * @param filename
     * @param inputStream
     * @return
     */
    @Async
    public  void  uploadAoleFile(String  filename, InputStream inputStream) throws IOException {
        OSSClient ossClient=null;
        try{
            ossClient = OSSUtils.getOSSClient(OSSConstant.AOLE_ENDPOINT, OSSConstant.ACCESS_KEY_ID, OSSConstant.ACCESS_KEY_SECRET);
            ossClient.putObject(OSSConstant.AOLE_BUCKET_NAME, filename,inputStream);
        }catch (Exception e){
            logger.info("国内上传出现异常"+e.getMessage());
        }finally {
            inputStream.close();
            ossClient.shutdown();

        }
    }

    /**
     * 国外上传
     * @param filename
     * @param inputStream
     * @return
     */
    @Async
    public  void uploadAuFile(String  filename, InputStream inputStream) throws IOException {
        OSSClient ossClient=null;
        try{
            ossClient = OSSUtils.getOSSClient(OSSConstant.AOLE_AU_ENDPOINT,OSSConstant.ACCESS_KEY_ID, OSSConstant.ACCESS_KEY_SECRET);
            ossClient.putObject(OSSConstant.AU_BUCKET_NAME, filename,inputStream);
        }catch (Exception e){
            logger.info("国外上传出现异常"+e.getMessage());
        }finally {
            inputStream.close();
            ossClient.shutdown();
        }
    }
}

发表评论
评论通过审核之后才会显示。
文章分类
联系方式
联系人: 郑州-小万
电话: 13803993919
Email: 1027060531@qq.com
QQ: 1027060531
网址: www.wanhejia.com