要将 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 类是自定义的,根据实际情况进行修改。

Java 如何将 HashMap<String, RooM> 类型存入和取出 Redis

原文地址: https://www.cveoy.top/t/topic/qvTq 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录