Kotlin - Spring Boot - WebFlux - Video Streaming example

Hello everyone, today I am going to show you how to stream a video using Spring Boot + WebFlux. 
Streaming means the continuous transmission of video files from a server to a client. You can download the source code from our Github repository.

For more topics, click the below link:


User Interface



Project Structure



Gradle Build(build.gradle.kts) 

import org.jetbrains.kotlin.gradle.tasks.KotlinCompile

plugins {
id("org.springframework.boot") version "2.5.4"
id("io.spring.dependency-management") version "1.0.11.RELEASE"
kotlin("jvm") version "1.5.21"
kotlin("plugin.spring") version "1.5.21"
}

group = "com.knf"
version = "0.0.1-SNAPSHOT"
java.sourceCompatibility = JavaVersion.VERSION_11

repositories {
mavenCentral()
}

dependencies {
implementation("org.springframework.boot:spring-boot-starter-webflux")
implementation("com.fasterxml.jackson.module:jackson-module-kotlin")
implementation("io.projectreactor.kotlin:reactor-kotlin-extensions")
implementation("org.jetbrains.kotlin:kotlin-reflect")
implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8")
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-reactor")
testImplementation("org.springframework.boot:spring-boot-starter-test")
testImplementation("io.projectreactor:reactor-test")
}

tasks.withType<KotlinCompile> {
kotlinOptions {
freeCompilerArgs = listOf("-Xjsr305=strict")
jvmTarget = "11"
}
}

tasks.withType<Test> {
useJUnitPlatform()
}


Controller(VideoStreamingController.kt)

package com.knf.springkotlinwebfluxvideostreaming.controller

import com.knf.springkotlinwebfluxvideostreaming.service.VideoStreamingService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.core.io.Resource
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.RequestHeader
import org.springframework.web.bind.annotation.RestController
import reactor.core.publisher.Mono

@RestController
class VideoStreamingController {
@Autowired
private val service: VideoStreamingService? = null
@GetMapping(value = ["video/{name}"], produces = ["video/mp4"])
fun getVideo(
@PathVariable title: String?,
@RequestHeader("Range") range: String?
): Mono<Resource> {
return service!!.getVideo(title)
}
}


Service(VideoStreamingService.kt)

package com.knf.springkotlinwebfluxvideostreaming.service

import org.springframework.beans.factory.annotation.Autowired
import org.springframework.core.io.ResourceLoader
import reactor.core.publisher.Mono
import com.knf.springkotlinwebfluxvideostreaming.service.VideoStreamingService
import org.springframework.core.io.Resource
import org.springframework.stereotype.Service

@Service
class VideoStreamingService {
@Autowired
private val resourceLoader: ResourceLoader? = null
fun getVideo(title: String?): Mono<Resource> {
return Mono.fromSupplier { resourceLoader!!.
                           getResource(String.format(FORMAT, title)) }
}

companion object {
private const val FORMAT = "classpath:mp4/%s.mp4"
}
}

Configuration(EndPointConfig.kt)

package com.knf.springkotlinwebfluxvideostreaming.config

import com.knf.springkotlinwebfluxvideostreaming.service.VideoStreamingService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.core.io.Resource
import org.springframework.http.MediaType
import org.springframework.web.reactive.function.server.*
import reactor.core.publisher.Mono

@Configuration
class EndPointConfig {
@Autowired
private val service: VideoStreamingService? = null
@Bean
fun router(): RouterFunction<ServerResponse> {
return RouterFunctions.route()
.GET(
"video/{name}",
HandlerFunction<ServerResponse> { serverRequest: ServerRequest ->
                                       videoHandler(serverRequest) })
.build()
}

private fun videoHandler(serverRequest: ServerRequest): Mono<ServerResponse> {
val title: String = serverRequest.pathVariable("name")
return ServerResponse.ok()
.contentType(MediaType.valueOf("video/mp4"))
.body(service!!.getVideo(title), Resource::class.java)
}
}

Main Class(SpringkotlinwebfluxvideostreamingApplication.kt)

package com.knf.springkotlinwebfluxvideostreaming

import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication

@SpringBootApplication
class SpringkotlinwebfluxvideostreamingApplication

fun main(args: Array<String>) {
runApplication<SpringkotlinwebfluxvideostreamingApplication>(*args)
}

index.html

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist
                                        /css/bootstrap.min.css">

<title>Kotlin Spring WebFlux Video Streaming</title>
</head>
<body>

<div class="container">
<h2>Kotlin Spring WebFlux Video Streaming Example</h2>
<video src="video/sample_960x540" width="750px" height="500px"
                                      controls preload="none">

</video>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">
                                                      </script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js
                                    /bootstrap.bundle.min.js" ></script>

</body>
</html>

Run - Spring Boot Application 





More related topics,

Java - Angular - VueJS - ReactJS

NodeJS - Angular - VueJS - ReactJS

Python - Flask  - Angular - VueJS - ReactJS

Popular posts from this blog

Spring boot video streaming example-HTML5

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Spring Boot + Mockito simple application with 100% code coverage

Spring Boot + OpenCSV Export Data to CSV Example

Custom Exception Handling in Quarkus REST API

DataTable-Pagination example with Spring boot, jQuery and ajax

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Node JS mini projects with source code - free download

Spring boot web project free download:User Registration System

Java - Blowfish Encryption and decryption Example