Skip to content

Instantly share code, notes, and snippets.

@retheviper
Last active May 5, 2022 13:14
Show Gist options
  • Save retheviper/d97ca50778267d0ab6cbf22b5ece4811 to your computer and use it in GitHub Desktop.
Save retheviper/d97ca50778267d0ab6cbf22b5ece4811 to your computer and use it in GitHub Desktop.
Spring MVC coroutine example
@RestController
@RequestMapping("/requests")
class CoroutineNetworkRequestController {
private val url = "https://en.wikipedia.org/api/rest_v1/page/summary"
private val logger = LogManager.getLogger(CoroutineNetworkRequestController::class.java)
/**
* do request with async and awaitAll
*/
@GetMapping("/async")
suspend fun requestAsync(): List<String?> {
logger.info("Request with async...")
var result: List<String?>
val time = measureTimeMillis {
coroutineScope {
val java = async { get("$url/Java") }
val kotlin = async { get("$url/Kotlin") }
logger.info("Waiting for results...")
result = awaitAll(java, kotlin)
logger.info("Results received!")
}
}
logger.info("Time: $time") // less than 2000ms
return result
}
/**
* do request without async and awaitAll
*/
@GetMapping
suspend fun request(): List<String?> {
logger.info("Request with sequential execution...")
var result: List<String?>
val time = measureTimeMillis {
val java = get("$url/Java")
val kotlin = get("$url/Kotlin")
logger.info("Waiting for results...")
result = listOf(java, kotlin)
logger.info("Results received!")
}
logger.info("Time: $time") // more than 2000ms
return result
}
private suspend fun get(url: String): String? {
logger.info("Requesting $url...")
delay(1000L)
return withContext(Dispatchers.IO) {
RestTemplate().getForObject(url, String::class.java)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment