这个错误通常发生在Redis操作时,将非String类型的值存储到Redis中,但是在获取时尝试将其转换为String类型

  1. 这里创建对象然后添加进List集合中,将集合转换为Map 将整个Map集合存入redis中
    List vehicleRegistrationPlaceCodes = new ArrayList();vehicleRegistrationPlaceCodes.add(new VehicleRegistrationPlaceCode(1L,"冀A","石家庄","河北","HB","130100","130000"));vehicleRegistrationPlaceCodes.add(new VehicleRegistrationPlaceCode(1L,"冀B","唐山","河北","HB","130200","130000"));vehicleRegistrationPlaceCodes.add(new VehicleRegistrationPlaceCode(1L,"冀C","秦皇岛","河北","HB","130300","130000"));vehicleRegistrationPlaceCodes.add(new VehicleRegistrationPlaceCode(1L,"冀D","邯郸","河北","HB","130400","130000"));Map collect = vehicleRegistrationPlaceCodes.stream().collect(Collectors.toMap(VehicleRegistrationPlaceCode::getPlatePrefix, Function.identity()));redisTemplate.boundHashOps("vehicleRegionCode").putAll(collect);

    这样直接存入就会报cannot be cast to java.lang.String 错误

  2. 将对象转换为json格式重新存入redis中程序正常运行

    redisTemplate.boundHashOps("vehicleRegionCode").put(vehicleRegistrationPlaceCode.getPlatePrefix(),JSONObject.toJSONString(vehicleRegistrationPlaceCode));