博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
kotlin使用spring data redis(二)
阅读量:6440 次
发布时间:2019-06-23

本文共 4392 字,大约阅读时间需要 14 分钟。

hot3.png

自定义序列化器

1.标准json序列化器,时间类型禁用时间戳

import com.fasterxml.jackson.core.JsonProcessingExceptionimport com.fasterxml.jackson.databind.ObjectMapperimport com.fasterxml.jackson.databind.SerializationFeatureimport com.fasterxml.jackson.datatype.jdk8.Jdk8Moduleimport com.fasterxml.jackson.datatype.jsr310.JavaTimeModuleimport com.fasterxml.jackson.module.kotlin.jacksonObjectMapperimport com.fasterxml.jackson.module.kotlin.readValueimport org.springframework.data.redis.serializer.RedisSerializerimport org.springframework.data.redis.serializer.SerializationExceptionopen class Jackson2Serializer : RedisSerializer
{ private var mapper: ObjectMapper = jacksonObjectMapper() init { mapper.registerModules(Jdk8Module(), JavaTimeModule()) mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) } override fun serialize(t: Any?): ByteArray? { if (t == null) { return ByteArray(0) } try { return mapper.writeValueAsBytes(t) } catch (e: JsonProcessingException) { throw SerializationException("Could not write JSON: " + e.message, e) } } override fun deserialize(bytes: ByteArray?): Any? { if (bytes == null) { return null } try { return mapper.readValue(bytes) } catch (e: Exception) { throw SerializationException("Could not read JSON: " + e.message, e) } }}

2.支持压缩(zstd)

import com.fasterxml.jackson.core.JsonProcessingExceptionimport com.github.luben.zstd.Zstdimport org.springframework.data.redis.serializer.SerializationExceptionimport java.lang.Exceptionclass Jackson2ZstdSerializer : Jackson2Serializer() {    override fun serialize(t: Any?): ByteArray? {        if (t == null) {            return ByteArray(0)        }        try {            val json = super.serialize(t)            val compressContent = Zstd.compress(json)            val compressHeader = "zstd_${json!!.size}_".toByteArray()            return compressHeader + compressContent        } catch (e: JsonProcessingException) {            throw e        } catch (ex: Exception) {            throw SerializationException("Could not compress JSON: " + ex.message, ex)        }    }    override fun deserialize(bytes: ByteArray?): Any? {        if (bytes == null) {            return null        }        try {            var counter = 0            bytes.forEachIndexed { index, byte ->                run {                    if (byte == '_'.toByte()) {                        counter++                        if(counter == 2){                            counter = index                            return@forEachIndexed                        }                    }                }            }            val compressHeader = bytes.sliceArray(0..counter)            val compressHeaderString = String(compressHeader)            if (!compressHeaderString.contains("zstd")) {                return null            }            val originContentLength = "[0-9]+".toRegex().find(compressHeaderString)?.value ?: return null            val compressContent = bytes.sliceArray((counter + 1)..(bytes.size - 1))            val decompressLength = if (compressContent.size > originContentLength.length) compressContent.size else originContentLength.length            val decompressContent = Zstd.decompress(compressContent, decompressLength)            return super.deserialize(decompressContent)        } catch (e: Exception) {            throw SerializationException("Could not read JSON: " + e.message, e)        }    }

3.启用Jackson2ZstdSerializer

@Configurationclass RedisCacheAutoConfiguration {    @Bean    fun redisTemplate(redisConnectionFactory: LettuceConnectionFactory): RedisTemplate
{ val template = RedisTemplate
() template.keySerializer = StringRedisSerializer() template.valueSerializer = Jackson2ZstdSerializer() template.setConnectionFactory(redisConnectionFactory) return template }}

4.用起来吧

@Autowired  private lateinit var redisTemplate: RedisTemplate
redisTemplate.opsForValue().set("aaa","aa",100,TimeUnit.SECONDS) val p = Passenger(1,"zhangsan", LocalDateTime.parse("2018-08-09T12:33:22.123")) redisTemplate.opsForValue().set("user",p,100,TimeUnit.SECONDS)

5.用Redis Desk Manager看一下

转载于:https://my.oschina.net/weidedong/blog/2218577

你可能感兴趣的文章
动态代理之投鞭断流
查看>>
栈(Stack)
查看>>
GitBlit hooks 简单的分支保护与控制
查看>>
mysql 主从备库重起初始化relay log 失败的处理
查看>>
解决eclipse中打开xml文件时不显示namespace标签的问题
查看>>
vue教程推荐
查看>>
java基础:==、equals()和hashcode()
查看>>
Mariadb安装、Apache安装
查看>>
输出有效成绩的前三名
查看>>
spark 机器学习分类
查看>>
linux系统管理技巧-日常基础命令三
查看>>
11.25 配置防盗链 11.26 访问控制Directory 11.27 访问控制FilesMat
查看>>
Python 回调和首参数绑定
查看>>
今天的学习
查看>>
美团点评基于 MGR 的 CMDB 高可用架构搭建之路
查看>>
Kafka如何做到1秒处理1500万条消息?
查看>>
设计模式“6”大原则!
查看>>
Nginx可以做什么?看完这篇你就懂了
查看>>
【C++】智能指针简述(四):shared_ptr
查看>>
three.js入门(三):点光源+动画的实现
查看>>