Environment set up

  1. Typically, a project will create a separate VOD video service to operate on the video.

  2. Configure the aliyun basic environment and obtain the AccessKey and AccessKey Secret. (See “Spring Cloud integrates Aliyun OSS to complete profile picture uploading function” for details)

  3. Download and install the JAR package

    Aliyun-java-vod-upload-1.4.5.jar is required if you want to implement uploading video.

    Because aliyun-java-vod-upload-1.4.5.jar is not officially open source, it needs to be downloaded separately and installed into Maven’s local repository.

    Open the command line in the directory where you downloaded the jar package and type:

    MVN install: install-file-dgroupid =com. aliyun-dartifactid = aliyun-sdk-vod-upload-dversion =1.4.5 -dpackaging =jar MVN install: install-file-dgroupid =com. aliyun-dartifactid = aliyun-sdk-vod-upload-dversion =1.4.5 -dpackaging =jar - Dfile = aliyun - Java - vod - upload - 1.4.5. JarCopy the code

    Note:

    If the command does not run, it indicates that Maven has not been downloaded or environment variables are not configured for Maven. Run the: MVN -v command to test whether the command can be executed.

  4. Import dependencies in POM.xml

    <dependencies>
        <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.oss</groupId>
            <artifactId>aliyun-sdk-oss</artifactId>
            <version>3.1.0</version>
        </dependency>
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>aliyun-sdk-vod-upload</artifactId>
            <version>1.4.5</version>
        </dependency>
        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20170516</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.69</version>
        </dependency>
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.2</version>
        </dependency>
    </dependencies>
    
    <! -- Aliyun Vod service JAR package warehouse -->
    <repositories>
        <repository>
            <id>sonatype-nexus-staging</id>
            <name>Sonatype Nexus Staging</name>
            <url>https://oss.sonatype.org/service/local/staging/deploy/maven2/</url>
            <releases>
                <enabled>true</enabled>
            </releases>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </repository>
    </repositories>
    Copy the code
  5. The configuration application. Yml

    spring:
      .
      File upload configuration
      servlet:
        multipart:
          Limit a single video file to 1GB
          max-file-size: 1024MB
          max-request-size: 1024MB
    
    # Aliyun Vod
    aliyun:
      vod:
        file:
          keyid: xxxxxxxxxxxxxx
          keysecret: xxxxxxxxxxxxxxxxxxxxxxx
    Copy the code
  6. Creating a constant class

    @Component
    public class ConstantPropertiesUtils implements InitializingBean {
    
        @Value("${aliyun.vod.file.keyid}")
        private String keyId;
    
        @Value("${aliyun.vod.file.keysecret}")
        private String keySecret;
    
        public static String ACCESS_KEY_ID;
        public static String ACCESS_KEY_SECRET;
    
        // When reading application.yml, two constants are automatically assigned
        @Override
        public void afterPropertiesSet(a) throws Exception { ACCESS_KEY_ID = keyId; ACCESS_KEY_SECRET = keySecret; }}Copy the code

    Note: By default, the class variable reads configuration information from a configuration file already set by application.yml or the Configuration center (Nacos, Spring Cloud Config). If not, specify the configuration file in the class configuration annotation.

    @PropertySource("classpath:xxx.yml")
    Copy the code
  7. Create aliyun SDK tool class

    @Component
    public class AliyunVodSDKUtils {
    
        // Initialize the Vod client call object
        public static DefaultAcsClient initVodClient(String accessKeyId, String accessKeySecret) throws ClientException {
            // On-demand service access area
            String regionId = "cn-shanghai";
            DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessKeySecret);
            DefaultAcsClient client = new DefaultAcsClient(profile);
    
            // SDK calls depend on client objects
            return client;
        }
    
        public static DefaultAcsClient initVodClient(a) throws ClientException {
            return initVodClient(ConstantPropertiesUtils.ACCESS_KEY_ID, ConstantPropertiesUtils.ACCESS_KEY_SECRET);
        }
    
        /** * Get play address *@paramVideoId videoId *@returnGetPlayInfoResponse Gets video playback response data *@throws Exception
         */
        public static GetPlayInfoResponse getPlayInfo(String videoId) throws Exception {
            // Create a sending request client
            DefaultAcsClient client = initVodClient();
    
            GetPlayInfoRequest request = new GetPlayInfoRequest();
            request.setVideoId(videoId);
    
            return client.getAcsResponse(request);
        }
    
        /** * Get video information *@paramVideoId videoId *@returnGetVideoInfoResponse Gets video information response data *@throws Exception
         */
        public static GetVideoInfoResponse getVideoInfo(String videoId) throws Exception {
            // Create a sending request client
            DefaultAcsClient client = initVodClient();
    
            GetVideoInfoRequest request = new GetVideoInfoRequest();
            request.setVideoId(videoId);
    
            return client.getAcsResponse(request);
        }
    
        /** * Obtain media information *@paramPageNo Indicates the current page number *@paramPageSize pageSize *@returnSearchMediaResponse Response data of querying media asset information *@throws ClientException
         */
        public static SearchMediaResponse searchMedia(int pageNo, int pageSize) throws ClientException {
            // Create a sending request client
            DefaultAcsClient client = initVodClient();
    
            SearchMediaRequest request = new SearchMediaRequest();
            request.setFields("Title,CoverURL,Status");
            request.setPageNo(pageNo);
            request.setPageSize(pageSize);
            request.setSearchType("video");
            request.setSortBy("CreationTime:Desc");
    
            return client.getAcsResponse(request);
        }
    
        /** * Delete video *@paramVideoIds support passing in multiple videoIds, multiple of which are separated by commas@returnDeleteVideoResponse DeleteVideoResponse data *@throws Exception
         */
        public static DeleteVideoResponse deleteVideo(String videoIds) throws Exception {
            // Create a sending request client
            DefaultAcsClient client = initVodClient();
    
            DeleteVideoRequest request = new DeleteVideoRequest();
            request.setVideoIds(videoIds);
    
            returnclient.getAcsResponse(request); }}Copy the code

    Common method encapsulation (Service layer)

    1. Upload videos

    public String uploadVideo(MultipartFile video) {
        String videoId = null;
    
        try {
            String fileName = video.getOriginalFilename();
            String title = fileName.substring(0, fileName.lastIndexOf('. '));
            InputStream inputStream = video.getInputStream();
    
            // Create the request object
            UploadStreamRequest request = new UploadStreamRequest(
                ConstantPropertiesUtils.ACCESS_KEY_ID,
                ConstantPropertiesUtils.ACCESS_KEY_SECRET,
                title, fileName, inputStream);
    
            // Create a file uploader
            UploadVideoImpl uploader = new UploadVideoImpl();
    
            // Execute file upload
            UploadStreamResponse response = uploader.uploadStream(request);
            videoId = response.getVideoId();
        } catch (IOException e) {
            throw new VideoUploadException(ResponseEnum.VIDEO_UPLOAD_ERROR);
        }
    
        // If the upload was successful, return the videoId of the video
        return videoId;
    }
    Copy the code

    2. Delete the video

    public boolean deleteVideo(String videoId) {
        try {
            AliyunVodSDKUtils.deleteVideo(videoId);
        } catch (Exception e) {
            throw new VideoDeleteException(ResponseEnum.VIDEO_DELETE_ERROR);
        }
    
        return true;
    }
    Copy the code

    3. Obtain the video playback address

    public String getVideoPlayUrl(String videoId) {
        String playUrl = null;
    
        try {
            GetPlayInfoResponse response = AliyunVodSDKUtils.getPlayInfo(videoId);
            List<GetPlayInfoResponse.PlayInfo> playInfoList = response.getPlayInfoList();
    
            // Get the play address
            for(GetPlayInfoResponse.PlayInfo playInfo : playInfoList) { playUrl = playInfo.getPlayURL(); }}catch (Exception e) {
            e.printStackTrace();
        }
    
        return playUrl;
    }
    Copy the code

    4. Get the video cover address

    public String getVideoCoverUrl(String videoId) {
        String coverUrl = null;
        
        try {
            DefaultAcsClient client = AliyunVodSDKUtils.initVodClient();
            GetVideoInfoResponse response = AliyunVodSDKUtils.getVideoInfo(client, videoId);
            
            // Get the cover address
            coverUrl = response.getVideo().getCoverURL();
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        return coverUrl;
    }
    Copy the code

    5. Obtain the video list in pages

    public Map<String, Object> videoList(int pageNo, int pageSize) {
        Map<String, Object> videoMap = new HashMap<>();
        List<VideoVo> videoList = new ArrayList<>();
        
        try {
            SearchMediaResponse response = AliyunVodSDKUtils.searchMedia(pageNo, pageSize);
            
            if(response.getMediaList() ! =null && response.getMediaList().size() > 0) {
                videoMap.put("total", response.getTotal());
                
                for (SearchMediaResponse.Media media : response.getMediaList()) {
                    // Encapsulate the video response object
                    VideoVo videoVo = new VideoVo();
                    
                    // Get the video information on aliyun
                    String videoId = media.getVideo().getVideoId();
                    videoVo.setCoverUrl(media.getVideo().getCoverURL());
                    videoVo.setPlayUrl(getVideoPlayUrl(videoId));
                    
                    // Get the video information in the local database
                    Video video = findVideoByVideoId(videoId);
                    videoVo.setId(video.getId());
                    videoVo.setTitle(video.getTitle());
                    videoVo.setUploader(video.getUploader());
                    videoVo.setLikeCount(video.getLikeCount());
                    videoVo.setCollectCount(video.getCollectCount());
                    videoVo.setPlayCount(video.getPlayCount());
                    videoVo.setGmtCreate(video.getGmtCreate());
                    
                    videoList.add(videoVo);
                }
                videoMap.put("videoList", videoList); }}catch (ClientException e) {
            e.printStackTrace();
        }
    
        return videoMap;
    }
    Copy the code