|
| 1 | +package pmhsfelix.kotlin.coroutines; |
| 2 | + |
| 3 | +import com.fasterxml.jackson.databind.DeserializationFeature |
| 4 | +import com.fasterxml.jackson.databind.ObjectMapper |
| 5 | +import com.fasterxml.jackson.module.kotlin.readValue |
| 6 | +import com.fasterxml.jackson.module.kotlin.registerKotlinModule |
| 7 | +import kotlinx.coroutines.experimental.* |
| 8 | +import kotlinx.coroutines.experimental.future.await |
| 9 | +import kotlinx.coroutines.experimental.future.future |
| 10 | +import org.apache.http.HttpResponse |
| 11 | +import org.apache.http.client.methods.HttpGet |
| 12 | +import org.apache.http.concurrent.FutureCallback |
| 13 | +import org.asynchttpclient.DefaultAsyncHttpClient |
| 14 | +import org.asynchttpclient.Response |
| 15 | +import org.slf4j.LoggerFactory |
| 16 | +import org.springframework.boot.autoconfigure.SpringBootApplication |
| 17 | +import org.springframework.boot.runApplication |
| 18 | +import org.springframework.context.annotation.Bean |
| 19 | +import org.springframework.web.bind.annotation.GetMapping |
| 20 | +import org.springframework.web.bind.annotation.RequestMapping |
| 21 | +import org.springframework.web.bind.annotation.RestController |
| 22 | +import org.springframework.web.servlet.HandlerInterceptor |
| 23 | +import org.springframework.web.servlet.ModelAndView |
| 24 | +import org.springframework.web.servlet.config.annotation.InterceptorRegistry |
| 25 | +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer |
| 26 | +import java.util.concurrent.CompletableFuture |
| 27 | +import java.util.concurrent.atomic.AtomicInteger |
| 28 | +import javax.servlet.http.HttpServletRequest |
| 29 | +import javax.servlet.http.HttpServletResponse |
| 30 | +import org.apache.http.impl.nio.client.HttpAsyncClients |
| 31 | +import org.apache.http.impl.nio.client.CloseableHttpAsyncClient |
| 32 | +import org.springframework.web.context.request.async.DeferredResult |
| 33 | +import java.lang.Exception |
| 34 | +import java.util.concurrent.TimeoutException |
| 35 | +import kotlin.coroutines.experimental.* |
| 36 | + |
| 37 | + |
| 38 | +@SpringBootApplication |
| 39 | +class SpringApp { |
| 40 | + @Bean |
| 41 | + fun config() = object : WebMvcConfigurer { |
| 42 | + override fun addInterceptors(registry: InterceptorRegistry) { |
| 43 | + registry.addInterceptor(object : HandlerInterceptor { |
| 44 | + override fun preHandle(request: HttpServletRequest, |
| 45 | + response: HttpServletResponse, |
| 46 | + handler: Any): Boolean { |
| 47 | + val start = System.nanoTime() |
| 48 | + request.setAttribute("ts", start) |
| 49 | + return true |
| 50 | + } |
| 51 | + |
| 52 | + override fun postHandle(request: HttpServletRequest, |
| 53 | + response: HttpServletResponse, |
| 54 | + handler: Any, modelAndView: ModelAndView?) { |
| 55 | + val end = System.nanoTime() |
| 56 | + var start = request.getAttribute("ts") as Long |
| 57 | + log.info("Request to ${request.requestURI} took ${(end - start) / 1_000_000F} ms") |
| 58 | + } |
| 59 | + }) |
| 60 | + } |
| 61 | + } |
| 62 | +} |
| 63 | + |
| 64 | +fun main(args: Array<String>) { |
| 65 | + runApplication<SpringApp>(*args) |
| 66 | +} |
| 67 | + |
| 68 | +private val log = LoggerFactory.getLogger(ExampleController::class.java) |
| 69 | + |
| 70 | +@RestController |
| 71 | +@RequestMapping("/example") |
| 72 | +class ExampleController { |
| 73 | + |
| 74 | + val client = DefaultAsyncHttpClient() |
| 75 | + val mapper = ObjectMapper() |
| 76 | + .registerKotlinModule() |
| 77 | + .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) |
| 78 | + |
| 79 | + fun get(url: String): CompletableFuture<Response> = client.prepareGet(url).execute().toCompletableFuture() |
| 80 | + fun getGitHub(url: String) = client.prepareGet(url) |
| 81 | + .addHeader("Authorization", "Bearer 1088a73d4016f27cbc606400f351849c3de197eb") |
| 82 | + .execute() |
| 83 | + .toCompletableFuture() |
| 84 | + |
| 85 | + val apacheClient = HttpAsyncClients.createDefault().apply { start() } |
| 86 | + suspend fun apacheGetGitHub(url: String): HttpResponse { |
| 87 | + val get = HttpGet(url) |
| 88 | + get.addHeader("Authorization", "Bearer 1088a73d4016f27cbc606400f351849c3de197eb") |
| 89 | + return suspendCoroutine { cont -> |
| 90 | + apacheClient.execute(get, object : FutureCallback<HttpResponse> { |
| 91 | + override fun cancelled() { |
| 92 | + cont.resumeWithException(TimeoutException()) |
| 93 | + } |
| 94 | + |
| 95 | + override fun completed(result: HttpResponse?) { |
| 96 | + cont.resume(result!!) |
| 97 | + } |
| 98 | + |
| 99 | + override fun failed(ex: Exception?) { |
| 100 | + cont.resumeWithException(ex!!) |
| 101 | + } |
| 102 | + }) |
| 103 | + } |
| 104 | + } |
| 105 | + |
| 106 | + |
| 107 | + val counter = AtomicInteger() |
| 108 | + fun getId() = counter.getAndIncrement() |
| 109 | + |
| 110 | + @GetMapping("/1") |
| 111 | + fun get1(): CompletableFuture<String?> { |
| 112 | + val cf = CompletableFuture<String?>() |
| 113 | + get("http://httpbin.org/get") |
| 114 | + .thenAccept { resp -> |
| 115 | + val body = resp.responseBody |
| 116 | + client.close() |
| 117 | + cf.complete(body) |
| 118 | + } |
| 119 | + return cf |
| 120 | + } |
| 121 | + |
| 122 | + @GetMapping("/2") |
| 123 | + fun get2(): CompletableFuture<String?> = |
| 124 | + future { |
| 125 | + val resp = get("http://httpbin.org/get").await() |
| 126 | + resp.responseBody |
| 127 | + } |
| 128 | + |
| 129 | + @GetMapping("/3") |
| 130 | + fun get3(): CompletableFuture<List<RepoAndTagsModel>> = |
| 131 | + future { |
| 132 | + val id = getId() |
| 133 | + log.info("[$id] Getting repo list") |
| 134 | + val resp = getGitHub("https://api.github.com/users/ktorio/repos").await() |
| 135 | + val repoList = mapper.readValue<List<RepoModel>>(resp.responseBody) |
| 136 | + repoList.map { |
| 137 | + log.info("[$id] Getting ${it.tags_url}") |
| 138 | + val resp = getGitHub(it.tags_url).await() |
| 139 | + val tags = mapper.readValue<List<TagModel>>(resp.responseBody) |
| 140 | + RepoAndTagsModel(it.name, tags.map { it.name }) |
| 141 | + } |
| 142 | + } |
| 143 | + |
| 144 | + @GetMapping("/4") |
| 145 | + fun get4(): CompletableFuture<List<RepoAndTagsModel>> = |
| 146 | + future(Unconfined) { |
| 147 | + val id = getId() |
| 148 | + log.info("[$id] Getting repo list") |
| 149 | + val resp = getGitHub("https://api.github.com/users/ktorio/repos").await() |
| 150 | + val repoList = mapper.readValue<List<RepoModel>>(resp.responseBody) |
| 151 | + log.info("[$id] Getting tags for all repos") |
| 152 | + val reqs = repoList.map { TagAsyncResponse(it.name, getGitHub(it.tags_url)) } |
| 153 | + reqs.map { |
| 154 | + log.info("[$id] Waiting for response") |
| 155 | + val resp = it.response.await() |
| 156 | + val tags = mapper.readValue<List<TagModel>>(resp.responseBody) |
| 157 | + RepoAndTagsModel(it.repoName, tags.map { it.name }) |
| 158 | + } |
| 159 | + } |
| 160 | + |
| 161 | + |
| 162 | + @GetMapping("/5") |
| 163 | + fun get5(): CompletableFuture<List<RepoAndTagsModel>> = |
| 164 | + future(Unconfined) { |
| 165 | + val id = getId() |
| 166 | + log.info("[$id] Getting repo list") |
| 167 | + val resp = apacheGetGitHub("https://api.github.com/users/ktorio/repos") |
| 168 | + val repoList = mapper.readValue<List<RepoModel>>(resp.entity.content) |
| 169 | + log.info("[$id] Getting tags for all repos") |
| 170 | + val reqs = repoList.map { TagAsyncResponse(it.name, future(Unconfined) {apacheGetGitHub(it.tags_url)}) } |
| 171 | + reqs.map { |
| 172 | + log.info("[$id] Waiting for response") |
| 173 | + val resp = it.response.await() |
| 174 | + val tags = mapper.readValue<List<TagModel>>(resp.entity.content) |
| 175 | + RepoAndTagsModel(it.repoName, tags.map { it.name }) |
| 176 | + } |
| 177 | + } |
| 178 | + |
| 179 | + fun <T> deferred(block: suspend () -> T): DeferredResult<T> { |
| 180 | + val result = DeferredResult<T>() |
| 181 | + block.startCoroutine(object : Continuation<T> { |
| 182 | + override fun resume(value: T) { |
| 183 | + result.setResult(value) |
| 184 | + } |
| 185 | + |
| 186 | + override fun resumeWithException(exception: Throwable) { |
| 187 | + result.setErrorResult(exception) |
| 188 | + } |
| 189 | + |
| 190 | + override val context: CoroutineContext |
| 191 | + get() = EmptyCoroutineContext |
| 192 | + }) |
| 193 | + return result |
| 194 | + } |
| 195 | + |
| 196 | + @GetMapping("/tags") |
| 197 | + fun get6(): DeferredResult<List<RepoAndTags>> = |
| 198 | + deferred { |
| 199 | + getTagsForReposInOrgs("https://api.github.com/users/ktorio/repos") |
| 200 | + } |
| 201 | +} |
| 202 | + |
| 203 | + |
| 204 | +private data class TagAsyncResponse<T>(val repoName: String, val response: CompletableFuture<T>) |
| 205 | +private data class RepoModel(val name: String, val url: String, val tags_url: String) |
| 206 | +private data class TagModel(val name: String) |
| 207 | +data class RepoAndTagsModel(val name: String, val tags: List<String>) |
0 commit comments