https://kotlinlang.org logo
#ktor
Title
# ktor
a

andev

06/02/2020, 8:20 PM
Hi, my app is acting like a proxy between the client app and server. A client makes a request, if cached data is valid i.e. not expired, I serve him that, otherwise I make a request to the server, get data, cache it, and then serve it to the client. I wrote some code, but it's not thread-safe. How can I improve this so I do not make unnecessary requests to the server?
Copy code
fun Application.module() {
    val client = HttpClient(OkHttp) {
        install(JsonFeature) {
            serializer = GsonSerializer()
        }
    }
    var cached: Data? = null
    routing {
        get("/") {
            if (cached == null) {
                val new = client.get<Data>("<https://my-host.com/message>")
                cached = new
            }
            if (cached!!.expires < System.currentTimeMillis()) {
                val new = client.get<Data>("<https://my-host.com/message>")
                cached = new
            }
            call.respond(cached!!.message)
        }
    }
}

data class Data(val expires: Long, val message: String)
a

andev

06/02/2020, 8:49 PM
Thanks!
3 Views