springboot项目接入redis遇到问题

springboot项目接入redis遇到问题

redis使用代码

JsonObject data = new JsonObject();
    Object obj  =  redisUtil.get("1");
    if (obj != null) {
        System.out.println("redis:"+obj);
        data = (JsonObject) obj;
    }else {
        LogUtil.printHttpParameterLog(log, "获取省市区", MYTO_URL + Constants.INTERFACE_MYTO_REGION + paras, null);
        String responseStr = HttpClientUtil.sendHttpGet(MYTO_URL + Constants.INTERFACE_MYTO_REGION + paras);
        LogUtil.printHttpReturnLog(log, "获取省市区", responseStr);
        if (StringUtil.isNotEmpty(responseStr)) {
            JsonObject responseData = new JsonParser().parse(responseStr).getAsJsonObject();
            data = responseData.get("data").getAsJsonObject();
            Object redisStr = data;
           redisUtil.set("1", redisStr, Constants.REGION_REDIS_TIME);
        }
    }
    return data;

redis封装代码

 public boolean set(String key,Object value,long time){  
    try {  
        if(time>0){  
            redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);  
        }else{  
            set(key, value);  
        }  
        return true;  
    } catch (Exception e) {  
        e.printStackTrace();  
        return false;  
    }  
} 

 public Object get(String key){  
    return key==null?null:redisTemplate.opsForValue().get(key);  
} 

遇到异常

com.fasterxml.jackson.databind.JsonMappingException: JsonObject (through reference chain: com.google.gson.JsonObject[“asBoolean”])

java.lang.ClassCastException: java.lang.String cannot be cast to com.google.gson.JsonObject

解决方式

public JsonObject getRegion(Map<String, Object> reqMap) throws Exception {
    String paras="?";
    if(reqMap.get("parentCode") != null){
        paras=paras+"parentCode="+reqMap.get("parentCode").toString(); 
    }
    if(reqMap.get("allLeaf") != null){
        if(paras.length() == 1){
            paras=paras+"allLeaf="+reqMap.get("allLeaf").toString();
        }else{
            paras=paras+"&allLeaf="+reqMap.get("allLeaf").toString(); 
        }
    }
    if(paras.length() == 1){
        paras = "";
    }
 //返回结果
 JsonObject data = new JsonObject();
 Object obj  =  redisUtil.get(REGION_REDIS_PREFIX+Constants.REGION);//从redis中取值
  if (obj != null) {
      log.info("从redis中取省市区数据开始:"+obj);
      data = new JsonParser().parse(obj.toString()).getAsJsonObject();//将object转换为String再转换成JsonObject
    }else {
        String responseStr = HttpClientUtil.sendHttpGet(MYTO_URL + Constants.INTERFACE_MYTO_REGION + paras);
        if (StringUtil.isNotEmpty(responseStr)) {
            JsonObject responseData = new JsonParser().parse(responseStr).getAsJsonObject();
           ** data = responseData.get("data").getAsJsonObject();
              String regionStr = data.toString();** 
            redisUtil.set(REGION_REDIS_PREFIX+Constants.REGION, regionStr, Constants.REGION_REDIS_TIME);
        }
    }
    return data;

猜你喜欢

转载自blog.csdn.net/weixin_39248420/article/details/88416397