天天看點

springboot對接阿裡雲視訊點播

在阿裡雲的視訊點播官方文檔中,可以看到是有一個上傳SDK和一個服務端SDK的,上傳視訊可以用上傳SDK裡面的服務端SDK裡面的java上傳SDK,其他操作查詢删除什麼的隻能用服務端SDK裡面的javaSDK

點開java上傳SDK,可以看到有一個demo可以下載下傳

springboot對接阿裡雲視訊點播

下載下傳這個demo,這個demo不是一個maven項目

根據文檔中寫的,引入maven依賴,然後把demo裡面的代碼複制到我們的項目,發現裡面有幾個類是找不到的,比如UploadStreamRequest,這些類所在的包不是開源的,在demo中是有這個jar包的,就是下面這個包,自己用指令打到本地倉庫或者私庫。

springboot對接阿裡雲視訊點播

全部依賴:

<!-- 阿裡雲視訊點播 -->
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>aliyun-java-sdk-core</artifactId>
            <version>4.5.1</version>
        </dependency>
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>aliyun-java-sdk-vod</artifactId>
            <version>2.15.11</version>
        </dependency>
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>aliyun-java-vod-upload</artifactId>
            <version>1.4.14</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.62</version>
        </dependency>
        <dependency>
            <groupId>com.aliyun.oss</groupId>
            <artifactId>aliyun-sdk-oss</artifactId>
            <version>3.1.0</version>
        </dependency>
           

 然後我一開始用流方式上傳一直提示連接配接逾時,阿裡雲控制台也是一直顯示上傳中。用本地檔案上傳的方式就可以成功上傳,不确定什麼原因,可能是網絡原因。

過了幾個小時再去用流方式上傳就可以上傳成功了(這個問了阿裡雲客服也沒說清楚什麼原因)

代碼如下

import com.aliyun.vod.upload.impl.*;
import com.aliyun.vod.upload.req.*;
import com.aliyun.vod.upload.resp.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

/**
 * 阿裡雲上傳音視訊
 */
@Component
public class UploadVideoConfiguration {

    //賬号AK資訊請填寫(必選)
    @Value("${aliyun.accessKeyId}")
    private String accessKeyId;
    //賬号AK資訊請填寫(必選)
    @Value("${aliyun.accessKeySecret}")
    private String accessKeySecret;

    @Value("${aliyun.endPoint}")
    private String endPoint;

    private String callBackUrl;

    /**
     * 流式上傳接口
     *
     * @param title
     * @param fileName
     * @param inputStream
     */
    public UploadStreamResponse testUploadStream(String title, String fileName, InputStream inputStream,Long cateId,
                                                 String key) throws IOException {
        UploadStreamRequest request = new UploadStreamRequest(accessKeyId, accessKeySecret, title, fileName, inputStream);
        /* 是否使用預設水印(可選),指定模闆組ID時,根據模闆組配置确定是否使用預設水印*/
        //request.setShowWaterMark(true);
        /* 自定義消息回調設定,參數說明參考文檔 https://help.aliyun.com/document_detail/86952.html#UserData */
//        request.setUserData("{\"Extend\":{\"test\":\"www\",\"localId\":\"xxxx\"}," +
//                "\"MessageCallback\":{\"CallbackURL\":\"" + callBackUrl + "\"}}");
        /* 視訊分類ID(可選) */
        request.setCateId(cateId);
        /* 視訊标簽,多個用逗号分隔(可選) */
        //request.setTags("标簽1,标簽2");
        /* 視訊描述(可選) */
        //request.setDescription("視訊描述");
        /* 封面圖檔(可選) */
        //request.setCoverURL("http://cover.sample.com/sample.jpg");
        /* 模闆組ID(可選) */
        //request.setTemplateGroupId("8c4792cbc8694e7084fd5330e56a33d");
        /* 工作流ID(可選) */
        //request.setWorkflowId("d4430d07361f0*be1339577859b0177b");
        /* 存儲區域(可選) */
//        request.setStorageLocation(endPoint);
        /* 開啟預設上傳進度回調 */
        request.setPrintProgress(true);
        /* 設定自定義上傳進度回調 (必須繼承 VoDProgressListener) */
//        request.setProgressListener(new PutObjectProgressListener());
        request.setProgressListener(new MyVoDProgressListener(inputStream.available(),key));
        /* 設定應用ID*/
        //request.setAppId("app-1000000");
        /* 點播服務接入點 */
//        request.setApiRegionId("cn-shanghai");
        /* ECS部署區域*/
//        request.setEcsRegionId("cn-shanghai");

        UploadVideoImpl uploader = new UploadVideoImpl();
        UploadStreamResponse response = uploader.uploadStream(request);
        System.out.print("RequestId=" + response.getRequestId() + "\n");  //請求視訊點播服務的請求ID
        if (response.isSuccess()) {
            System.out.println("上傳成功!!!");
            System.out.print("VideoId=" + response.getVideoId() + "\n");
        } else { //如果設定回調URL無效,不影響視訊上傳,可以傳回VideoId同時會傳回錯誤碼。其他情況上傳失敗時,VideoId為空,此時需要根據傳回錯誤碼分析具體錯誤原因
            System.out.print("VideoId=" + response.getVideoId() + "\n");
            System.out.print("ErrorCode=" + response.getCode() + "\n");
            System.out.print("ErrorMessage=" + response.getMessage() + "\n");
        }
        return response;

    }

    /**
     * 本地檔案上傳接口
     *
     * @param title
     * @param fileName
     */
    public UploadVideoResponse testUploadVideo(String title, String fileName) {
        UploadVideoRequest request = new UploadVideoRequest(accessKeyId, accessKeySecret, title, fileName);
        /* 可指定分片上傳時每個分片的大小,預設為2M位元組 */
        request.setPartSize(2 * 1024 * 1024L);
        /* 可指定分片上傳時的并發線程數,預設為1,(注:該配置會占用伺服器CPU資源,需根據伺服器情況指定)*/
        request.setTaskNum(1);
        /* 是否開啟斷點續傳, 預設斷點續傳功能關閉。當網絡不穩定或者程式崩潰時,再次發起相同上傳請求,可以繼續未完成的上傳任務,适用于逾時3000秒仍不能上傳完成的大檔案。
        注意: 斷點續傳開啟後,會在上傳過程中将上傳位置寫入本地磁盤檔案,影響檔案上傳速度,請您根據實際情況選擇是否開啟*/
        //request.setEnableCheckpoint(false);
        /* OSS慢請求日志列印逾時時間,是指每個分片上傳時間超過該門檻值時會列印debug日志,如果想屏蔽此日志,請調整該門檻值。機關: 毫秒,預設為300000毫秒*/
        //request.setSlowRequestsThreshold(300000L);
        /* 可指定每個分片慢請求時列印日志的時間門檻值,預設為300s*/
        //request.setSlowReque stsThreshold(300000L);
        /* 是否顯示水印(可選),指定模闆組ID時,根據模闆組配置确定是否顯示水印*/
        //request.setIsShowWaterMark(true);
        /* 自定義消息回調設定(可選),參數說明參考文檔 https://help.aliyun.com/document_detail/86952.html#UserData */
        // request.setUserData("{\"Extend\":{\"test\":\"www\",\"localId\":\"xxxx\"},\"MessageCallback\":{\"CallbackURL\":\"http://test.test.com\"}}");
        /* 視訊分類ID(可選) */
        request.setCateId(1000325496L);
        /* 視訊标簽,多個用逗号分隔(可選) */
        //request.setTags("标簽1,标簽2");
        /* 視訊描述(可選) */
        //request.setDescription("視訊描述");
        /* 封面圖檔(可選) */
        //request.setCoverURL("http://cover.sample.com/sample.jpg");
        /* 模闆組ID(可選) */
        //request.setTemplateGroupId("8c4792cbc8694e7084fd5330e56a33d");
        /* 工作流ID(可選) */
        //request.setWorkflowId("d4430d07361f0*be1339577859b0177b");
        /* 存儲區域(可選) */
        //request.setStorageLocation("in-201703232118266-5sejdln9o.oss-cn-shanghai.aliyuncs.com");
        /* 開啟預設上傳進度回調 */
        //request.setPrintProgress(false);
        /* 設定自定義上傳進度回調 (必須繼承 VoDProgressListener) */
        //request.setProgressListener(new PutObjectProgressListener());
        /* 設定您實作的生成STS資訊的接口實作類*/
        // request.setVoDRefreshSTSTokenListener(new RefreshSTSTokenImpl());
        /* 設定應用ID*/
        //request.setAppId("app-1000000");
        /* 點播服務接入點 */
        //request.setApiRegionId("cn-shanghai");
        /* ECS部署區域*/
        // request.setEcsRegionId("cn-shanghai");
        UploadVideoImpl uploader = new UploadVideoImpl();
        UploadVideoResponse response = uploader.uploadVideo(request);
        System.out.print("RequestId=" + response.getRequestId() + "\n");  //請求視訊點播服務的請求ID
        if (response.isSuccess()) {
            System.out.print("VideoId=" + response.getVideoId() + "\n");
        } else {
            /* 如果設定回調URL無效,不影響視訊上傳,可以傳回VideoId同時會傳回錯誤碼。其他情況上傳失敗時,VideoId為空,此時需要根據傳回錯誤碼分析具體錯誤原因 */
            System.out.print("VideoId=" + response.getVideoId() + "\n");
            System.out.print("ErrorCode=" + response.getCode() + "\n");
            System.out.print("ErrorMessage=" + response.getMessage() + "\n");
        }
        return response;
    }
}
           

這邊這個進度監聽器是自己繼承它指定的那個監聽器類實作的,為了擷取上傳進度給前端用

/**
 * 阿裡雲上傳視訊擷取進度監聽器
 */
public class MyVoDProgressListener implements VoDProgressListener {

    private long bytesWritten = 0L;
    private long totalBytes = -1L;
    private boolean succeed = false;
    private String videoId;
    private String imageId;

    private String key;

    private static String redisHost = "127.0.0.1";
    private static int redisPort = 6379;
    private static String redisPass = "";

    public MyVoDProgressListener(long totalBytes,String key) {
        this.key = key;
        this.totalBytes = totalBytes;
    }

    public void progressChanged(ProgressEvent progressEvent) {
        long bytes = progressEvent.getBytes();
        ProgressEventType eventType = progressEvent.getEventType();
        switch(eventType) {
            case TRANSFER_STARTED_EVENT:
                if (this.videoId != null) {
                    System.out.println("開始上傳ID為" + this.videoId + "的視訊");
                }

                if (this.imageId != null) {
                    System.out.println("Start to upload imageId " + this.imageId + "......");
                }
                break;
            case REQUEST_CONTENT_LENGTH_EVENT:
                this.totalBytes = bytes;
                System.out.println(this.totalBytes + " bytes in total will be uploaded to OSS.");
                break;
            case REQUEST_BYTE_TRANSFER_EVENT:
                this.bytesWritten += bytes;
                if (this.totalBytes != -1L) {
                    int percent = (int)((double)this.bytesWritten * 100.0D / (double)this.totalBytes);
                    //上傳百分比存到redis,接口取出來返給前端
                    Jedis jedis = JedisUtil.getInstance();
                    jedis.set(this.key, String.valueOf(percent));
                    if(percent == 100){
                        jedis.close();
                    }
                    System.out.println(bytes + " bytes have been written at this time, upload progress: " + percent + "%(" + this.bytesWritten + "/" + this.totalBytes + ")");
                } else {
                    System.out.println(bytes + " bytes have been written at this time, upload sub total : (" + this.bytesWritten + ")");
                }
                break;
            case TRANSFER_COMPLETED_EVENT:
                this.succeed = true;
                if (this.videoId != null) {
                    System.out.println("視訊ID為 " + this.videoId + " , 總寫入位元組" + this.bytesWritten + "上傳完成");
                }

                if (this.imageId != null) {
                    System.out.println("Succeed to upload imageId " + this.imageId + " , " + this.bytesWritten + " bytes have been transferred in total.");
                }
                break;
            case TRANSFER_FAILED_EVENT:
                if (this.videoId != null) {
                    System.out.println("視訊ID為 " + this.videoId + " , 總寫入位元組" + this.bytesWritten + "上傳失敗");
                }

                if (this.imageId != null) {
                    System.out.println("Failed to upload imageId " + this.imageId + " , " + this.bytesWritten + " bytes have been transferred.");
                }
        }

    }

    public boolean isSucceed() {
        return this.succeed;
    }

    public void onVidReady(String videoId) {
        this.setVideoId(videoId);
    }

    public void onImageIdReady(String imageId) {
        this.setImageId(imageId);
    }

    public String getVideoId() {
        return this.videoId;
    }

    public void setVideoId(String videoId) {
        this.videoId = videoId;
    }

    public String getImageId() {
        return this.imageId;
    }

    public void setImageId(String imageId) {
        this.imageId = imageId;
    }
}
           

到這裡上傳視訊可以了,查詢視訊資訊和删除視訊的功能隻能用文檔裡面那個服務端SDK

springboot對接阿裡雲視訊點播

代碼如下:

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.vod.model.v20170321.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class VideoUtils {

    private DefaultAcsClient client;

    public VideoUtils(@Value("${aliyun.accessKeyId}") String accessKeyId,
                      @Value("${aliyun.accessKeySecret}") String accessKeySecret) {
        String regionId = "cn-shanghai";  // 點播服務接入區域
        DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessKeySecret);
        client = new DefaultAcsClient(profile);
    }

    /**
     * 擷取視訊資訊 帶播放位址
     *
     * @param videoId 視訊ID
     * @return GetVideoInfoResponse 擷取視訊資訊響應資料
     * @throws Exception
     */
    public GetMezzanineInfoResponse getVideoInfo(String videoId) throws Exception {
        GetMezzanineInfoRequest request = new GetMezzanineInfoRequest();
        request.setVideoId(videoId);
        return client.getAcsResponse(request);
    }

    /**
     * 根據ID删除
     *
     * @param videoIds ID
     * @return 是否成功
     */
    public boolean delVideoByVideoId(String videoIds) throws ClientException {
        DeleteVideoRequest request = new DeleteVideoRequest();
        request.setVideoIds(videoIds);

        client.getAcsResponse(request);
        return true;
    }
}