5つのストレージタイプを理解した後、string <String、Object>ですべてを保存できると言う友人もいます。コレクションオブジェクトは保存できます。はい、保存できます。ただし、文字列タイプのストレージオブジェクトなどはredisにシリアル化されてから、オブジェクトを取得するために逆シリアル化され、不要なオーバーヘッドが追加されます。。
- 文字列:単純な文字列、kvフォームを格納します
- リスト::コレクションデータを保存する
- ハッシュ:ストレージオブジェクト
- セット:繰り返されない要素
- zSet:繰り返されて順序付けされていないデータ(要素のスコアに従ってソートされます)
// String 字符串 普通的k v
ValueOperations<String, Object> string = redisTemplate.opsForValue();
string.set("string:one", "dugt is handsome"); // set
string.get("string:one"); // get
string.set("string:number", 1);
string.increment("string:number"); // +1 也可以自己设置加的数量
string.decrement("string:number"); // -1
string.setIfAbsent("string:ifAbsent", "hello"); // 如果不存在 则设置 返回true 存在返回false 不做处理
string.getAndSet("string:ifAbsent", "hello too"); // 获取并设置 如不存在返回null
// list 存储集合
ListOperations<String, Object> list = redisTemplate.opsForList();
list.leftPush("list:one", "dugt"); // 左边添加
list.rightPush("list:one", "dugt2"); // 右边添加
list.range("list:one", 0, -1); // 根据下标获取集合的元素 0~ -1 全部元素
list.leftPop("list:one"); // 弹出最左边元素,集合中会删除该元素
list.rightPop("list:one"); // 弹出最右边元素,集合中会删除该元素
list.leftPushAll("list:list", Arrays.asList(-1, 2, true)); // 从右边添加多个元素
list.size("list:list"); // 集合大小
// hash 存储对象
HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
hash.put("hash:one", "name", "dugt"); //添加对象
hash.put("hash:one", "age", 22);
hash.put("hash:one", "address", "潍坊");
hash.get("hash:one", "name"); // get
hash.delete("hash:one", "age") // del
hash.entries("hash:one"); // 获取对象
HashMap<String, Object> map = new HashMap<>(4);
map.put("du", 22);
map.put("address", "潍坊");
hash.putAll("hash:all", map); // 存储map
hash.hasKey("hash:one", "test"); // key对应的 map对象key是否存在
hash.keys("hash:one"); // 获取所有 map的key
hash.values("hash:one"); // 获取所有 map的value
// set 不重复的集合
SetOperations<String, Object> set = redisTemplate.opsForSet();
set.add("set:one", -1, 0, 2); // add
set.members("set:one"); // 获取元素
set.remove("set:one", 2); // 删除
// zSet 不重复且有序的集合 根据元素的score 分数排序
ZSetOperations<String, Object> zSet = redisTemplate.opsForZSet();
zSet.add("zSet:one", "hello", 1); // add 按元素的分数排序 分数小的在前
zSet.add("zSet:one", "name", 2);
zSet.range("zSet:one", 0, -1); // 获取元素
zSet.incrementScore("zSet:one", "hello", 5); // 给集合元素增加分数
zSet.score("zSet:one","hello"); // 获取分数
zSet.rank("zSet:one","hello"); // 获取名次
zSet.rangeByScore("zSet:one", 3, 10); // 根据分数区间获取元素
redisハッシュを共有するputAllオブジェクトツールクラス
@Lazy
@Component
public class RedisUtils {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
@SneakyThrows
public void hashPutAllObject(String key, Object object) {
Class aClass = object.getClass();
Field[] fields = aClass.getDeclaredFields();
final int mapInitCount = (int) (fields.length / 0.75F + 1F);
HashMap<String, Object> map = new HashMap<>(mapInitCount);
for (Field field : fields) {
field.setAccessible(true);
map.put(field.getName(), field.get(object));
}
redisTemplate.opsForHash().putAll(key, map);
}
}
推奨読書