Created
March 16, 2022 17:54
-
-
Save Blad3Mak3r/de7a734b4b40d4b42265269efefe9682 to your computer and use it in GitHub Desktop.
Redisson Codec for Kotlin JSON Serialization
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Serializable | |
data class Animal( | |
val id: Long, | |
val name: String | |
) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
val client = Redisson.create(...) | |
val list = client.getList<Animal>("animals", AnimalsSerializationCodec) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
object AnimalsSerializationCodec : BaseCodec() { | |
@OptIn(ExperimentalSerializationApi::class, InternalSerializationApi::class) | |
private val valueEncoder = Encoder { | |
val out = ByteBufAllocator.DEFAULT.buffer() | |
try { | |
val os = ByteBufOutputStream(out) | |
Json.encodeToStream(Animal.serializer(), it as Animal, os) | |
os.buffer() | |
} catch (e: IOException) { | |
out.release() | |
throw e | |
} catch (e: java.lang.Exception) { | |
out.release() | |
throw IOException(e) | |
} | |
} | |
@OptIn(ExperimentalSerializationApi::class) | |
private val valueDecoder = Decoder<Any> { buf, state -> | |
val content: Animal = Json.decodeFromStream(ByteBufInputStream(buf)) | |
content | |
} | |
override fun getValueDecoder(): Decoder<Any> { | |
return valueDecoder | |
} | |
override fun getValueEncoder(): Encoder { | |
return valueEncoder | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you for this gist!
A little more generic variation could look like this: