java如何往redis存入HashMapString RooM类型和取出
要将HashMap<String, RooM>类型存入Redis,需要将HashMap转换为Redis的数据结构。可以使用Redis的Hash数据类型来存储。
存入HashMap<String, RooM>类型到Redis的示例代码如下:
// 创建Redis连接
Jedis jedis = new Jedis("localhost", 6379);
// 创建HashMap
HashMap<String, RooM> map = new HashMap<>();
// 添加数据到HashMap
map.put("room1", new RooM("room1"));
map.put("room2", new RooM("room2"));
// 将HashMap转换为Map<String, String>
Map<String, String> redisMap = new HashMap<>();
for (Map.Entry<String, RooM> entry : map.entrySet()) {
redisMap.put(entry.getKey(), entry.getValue().toString());
}
// 存入Redis
jedis.hmset("rooms", redisMap);
// 关闭Redis连接
jedis.close();
要从Redis取出HashMap<String, RooM>类型,需要将Redis获取到的Hash数据类型转换为HashMap。
从Redis取出HashMap<String, RooM>类型的示例代码如下:
// 创建Redis连接
Jedis jedis = new Jedis("localhost", 6379);
// 从Redis获取Hash数据
Map<String, String> redisMap = jedis.hgetAll("rooms");
// 创建HashMap
HashMap<String, RooM> map = new HashMap<>();
// 遍历Redis获取到的数据,并转换为HashMap<String, RooM>
for (Map.Entry<String, String> entry : redisMap.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
// 将字符串转换为RooM对象
RooM room = new RooM(value);
// 添加到HashMap
map.put(key, room);
}
// 关闭Redis连接
jedis.close();
注意:上述示例代码中的RooM类是自定义的,根据实际情况进行修改
原文地址: https://www.cveoy.top/t/topic/iPNM 著作权归作者所有。请勿转载和采集!