redis如何實(shí)現(xiàn)保存對(duì)象
redis保存對(duì)象
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
保存對(duì)象
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;
}
}


測(cè)試成功。
redis存放對(duì)象的兩種方式
數(shù)據(jù)格式
- 用戶id為查找的key
- 存儲(chǔ)的value用戶對(duì)象包括姓名,年齡,生日等等
- 如果用普通的key-value結(jié)構(gòu)來(lái)存儲(chǔ),主要有以下2種方式存儲(chǔ)
方式一(String)

這種方式是使用list或者set這些來(lái)存儲(chǔ)的,這樣的方式其實(shí)也可以達(dá)到我們想要的效果,但是因?yàn)槊看涡薷膶傩远夹枰阶?,性能開銷非常大。1.先反序列化;2,修改;3.序列化
方式二(hash)
這種方式其實(shí)也有兩種寫法
寫法一:

這種寫法不僅能夠達(dá)成目標(biāo),而且解決了資源消耗過(guò)大的問(wèn)題,但是也引起了另一個(gè)問(wèn)題,就是用戶的id數(shù)據(jù)冗余
寫法二:

通過(guò)key(用戶id)+field(屬性標(biāo)簽)可以操作對(duì)應(yīng)屬性數(shù)據(jù)了,既不需要重復(fù)存儲(chǔ)數(shù)據(jù),也不會(huì)帶來(lái)序列化和并修復(fù)操控的問(wèn)題
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持本站。
版權(quán)聲明:本站文章來(lái)源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請(qǐng)保持原文完整并注明來(lái)源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非maisonbaluchon.cn所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來(lái)源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來(lái),僅供學(xué)習(xí)參考,不代表本站立場(chǎng),如有內(nèi)容涉嫌侵權(quán),請(qǐng)聯(lián)系alex-e#qq.com處理。
關(guān)注官方微信