问题描述:
我单独写了一个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转成功了~