记Redis @type一个坑

问题描述:

我单独写了一个jar项目是用来更新redis的  然后主项目会去读取redis中更新完之后的数据 但是主项目读取的时候发现@type路径不一样 导致映射不了实体类就会报错为一个转换异常

jar项目的实体路径为: com.xyz.miniLegion.entity.OpenNotice

主项目的实体路径为: com.qr.gameServer100.entity.OpenNotice

 导致主项目去redis中获取jar项目写进去的value对应的type不一致

罪魁祸首就是SerializerFeature.WriteClassName这个序列化


public static String getString(Object object) {
   return JSON.toJSONString(object, SerializerFeature.WriteClassName);
}

如果加了SerializerFeature.WriteClassName存进redis当中的实体类就会带@type路径地址

//"@type":"com.xyz.miniLegion.entity.OpenNotice"

问题解决方案:去掉@type 或者 两边@type路径存放路径一致 (包名和实体类修改为一致)

去掉@type使用 JSONObject.toJSONString(obj)来存value实体类

    /**
     * hashMap存值方式
     *
     * @param parentKey
     * @param fieldKey
     * @param obj
     */
    public static void hashSet(String parentKey, String fieldKey, Object obj) {
        try {
            jedis.hset(parentKey, fieldKey, JSONObject.toJSONString(obj));
            //jedis.hset(parentKey, fieldKey, JSONParser.getString(obj)); //"@type":"com.xyz.miniLegion.entity.OpenNotice"
        } finally {
            jedis.close();
        }
    }

获取hashAll数据

   /**
     * 获取hashGetAll
     * @param parentKey
     * @return
     */
    public Map<String, String> hashGetAll(String parentKey) {
        try (Jedis jedis = pools.getResource()) { //这种写法不需要手动close();
            return jedis.hgetAll(parentKey);
        }catch (Exception e) {      
            return null;
        }
    }

测试Redis转实体类

   @Test
    void getSoldierAttribute() {
        Map<String, String> openNoticeMap = redisPoolMgr.hashGetAll(StaticData.OpenNotice);
        //第一种根据key循环
        for (String key : openNoticeMap.keySet()) {
            OpenNotice openNotice = JSONObject.parseObject(openNoticeMap.get(key), OpenNotice.class);
            System.out.println("根据key循环:" +openNotice.getContent());
            System.out.println("根据key循环:" + JSONObject.toJSONString(openNotice));
        }

        //第二种根据value循环
        for (String values : openNoticeMap.values()) {
            OpenNotice openNotice = JSONObject.parseObject(values, OpenNotice.class);
            System.out.println("根据value循环:"+openNotice.getContent());
            System.out.println("根据value循环:" + JSONObject.toJSONString(openNotice));
        }
    }

ok转成功了~

  • 6
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值