redis如何實現(xiàn)保存對象
redis保存對象
redis數(shù)據(jù)結(jié)構(gòu)
String
——字符串Hash
——字典List
——列表Set
——集合Sorted Set
——有序集合
redisTemplate.opsForValue();//操作字符串 redisTemplate.opsForHash();//操作hash redisTemplate.opsForList();//操作list redisTemplate.opsForSet();//操作set redisTemplate.opsForZSet();//操作有序set
保存對象
RedisConfig.java
package com.wj.demo.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer; import org.springframework.data.redis.serializer.StringRedisSerializer; @Configuration public class RedisConfig { @Bean public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) { RedisTemplate<String, Object> template = new RedisTemplate<String, Object>(); template.setConnectionFactory(redisConnectionFactory); template.setKeySerializer(new StringRedisSerializer()); template.setValueSerializer(new GenericJackson2JsonRedisSerializer()); template.setHashKeySerializer(new GenericJackson2JsonRedisSerializer()); template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer()); template.afterPropertiesSet(); return template; } }
測試成功。
redis存放對象的兩種方式
數(shù)據(jù)格式
- 用戶id為查找的key
- 存儲的value用戶對象包括姓名,年齡,生日等等
- 如果用普通的key-value結(jié)構(gòu)來存儲,主要有以下2種方式存儲
方式一(String)
這種方式是使用list或者set這些來存儲的,這樣的方式其實也可以達(dá)到我們想要的效果,但是因為每次修改屬性都需要三步走,性能開銷非常大。1.先反序列化;2,修改;3.序列化
方式二(hash)
這種方式其實也有兩種寫法
寫法一:
這種寫法不僅能夠達(dá)成目標(biāo),而且解決了資源消耗過大的問題,但是也引起了另一個問題,就是用戶的id數(shù)據(jù)冗余
寫法二:
通過key(用戶id)+field(屬性標(biāo)簽)可以操作對應(yīng)屬性數(shù)據(jù)了,既不需要重復(fù)存儲數(shù)據(jù),也不會帶來序列化和并修復(fù)操控的問題
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持本站。
版權(quán)聲明:本站文章來源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請聯(lián)系alex-e#qq.com處理。