共計 1785 個字符,預計需要花費 5 分鐘才能閱讀完成。
本篇內容主要講解“Redis 怎么實現保存對象”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓丸趣 TV 小編來帶大家學習“Redis 怎么實現保存對象”吧!
redis 保存對象 redis 數據結構
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 存放對象的兩種方式數據格式
用戶 id 為查找的 key
存儲的 value 用戶對象包括姓名,年齡,生日等等
如果用普通的 key-value 結構來存儲,主要有以下 2 種方式存儲
方式一(String)
這種方式是使用 list 或者 set 這些來存儲的,這樣的方式其實也可以達到我們想要的效果,但是因為每次修改屬性都需要三步走,性能開銷非常大。1. 先反序列化;2,修改;3. 序列化
方式二(hash)
這種方式其實也有兩種寫法
寫法一:
這種寫法不僅能夠達成目標,而且解決了資源消耗過大的問題,但是也引起了另一個問題,就是用戶的 id 數據冗余
寫法二:
通過 key(用戶 id)+field(屬性標簽)可以操作對應屬性數據了,既不需要重復存儲數據,也不會帶來序列化和并修復操控的問題
到此,相信大家對“Redis 怎么實現保存對象”有了更深的了解,不妨來實際操作一番吧!這里是丸趣 TV 網站,更多相關內容可以進入相關頻道進行查詢,關注我們,繼續學習!