Skip to content

Streaming vs data objects

You can choose between using the streaming-based API or the data-object based API.

Data objects

The data object based API uses basic types such as String, ByteArray, Long, Double, etc... Keys are always String (feel free to use the low-level API if you require binary keys).

val fooValue: String? = connection.getString("foo")
val fooValueBytes: ByteArray? = connection.getBytes("foo")

Hash commands

Redis supports binary field names, but kotlin-redis has APIs which assume String. If you require binary field names, you can achieve this easily by writing your own API on top of the core API, see Custom commands

Streaming API

Values can be transferred as a StreamWithLength (an InputStream plus its length), so large values are never held in memory.

Note that when handling a response, the InputStream must be consumed before the connection can be used for anything else.

// get using streaming
var fooValueBytes: ByteArray? = null
connection.getStreaming("foo") {
    if (it != null) {
        val outStream = ByteArrayOutputStream(it.len)
        it.s.copyTo(outStream)
        fooValueBytes = outStream.toByteArray()
    }
}

Example 1 - Upload a file using streaming

Upload a file using SET in streaming mode:

val file = Path.of("large.bin")
file.inputStream().buffered().use { input ->
    conn.set("large", StreamWithLength(file.fileSize().toInt(), input))
}

Example 2 - Download a value using streaming

Download a large value into a file using GET in streaming mode:

conn.getStreaming("large") { s ->
    // s is null if the key does not exist
    if (s != null) {
        Path.of("download.bin").outputStream().buffered().use { s.s.copyTo(it) }
    }
}
The stream reads directly from the connection, so consume it inside the callback.