package com.hikvision.building.cloud.neptune.community.biz.service; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Service; import com.fasterxml.jackson.core.type.TypeReference; import com.hikvision.building.cloud.neptune.community.biz.Utils.FileUtils; import com.hikvision.building.cloud.neptune.community.biz.Utils.JSONUtil; import com.hikvision.building.cloud.neptune.community.biz.constant.Constant; import com.hikvision.building.cloud.neptune.community.biz.vo.Province; /** * * @author xujian18 * @version 2017年11月13日下午17:47 * @since 2017年11月13日 */ @Service public class ProvinceCityService { @Autowired private StringRedisTemplate provinceTemplate; final List<Province> provinces=parseProvince("province/provinces.json"); final List<Province> cities=parseProvince("province/cities.json"); final List<Province> areas=parseProvince("province/areas.json"); public List<Province> findProvinceCityByParentId(String parentId) { List<Province> all=new ArrayList<>(); List<Province> news=new ArrayList<>(); //缓存没有 String j = provinceTemplate.opsForValue().get(Constant.PROVINCE_CITY_AREA ); if(StringUtils.isBlank(j)){ all.addAll(provinces); all.addAll(cities); all.addAll(areas); if(StringUtils.isBlank(parentId)){ return provinces; }else{ for(Province p:all){ if(StringUtils.isNotBlank(p.getParent_code())){ if(p.getParent_code().equals(parentId)){ news.add(p); } } } String json = JSONUtil.toJson(all); provinceTemplate.opsForValue().set(Constant.PROVINCE_CITY_AREA , json ,1, TimeUnit.DAYS); return news; } }else{ //缓存有 TypeReference<List<Province>> typeReference = new TypeReference<List<Province>>(){}; List<Province> collection = JSONUtil.toCollection(j, typeReference); for(Province p:collection){ if(StringUtils.isNotBlank(p.getParent_code())){ if(p.getParent_code().equals(parentId)){ news.add(p); } }else{ all.add(p); } } if(StringUtils.isBlank(parentId)){ return all; }else{ return news; } } } private List<Province> parseProvince(String area) { String JsonContext = null; try { if(System.getProperty("os.name")!=null && System.getProperty("os.name").contains("Windows")){ area = this.getClass().getClassLoader().getResource(area).getPath(); }else{ area = "/neptune-community/" + area; } JsonContext = new FileUtils().ReadFile(area); } catch (IOException e) { throw new RuntimeException(e); } TypeReference<List<Province>> typeReference = new TypeReference<List<Province>>(){}; List<Province> collection = JSONUtil.toCollection(JsonContext,typeReference ); return collection; } public static void main(String[] args) { ProvinceCityService sss = new ProvinceCityService(); System.out.println(sss.areas.size()); System.out.println(sss.cities.size()); System.out.println(sss.provinces.size()); } }
package com.hikvision.building.cloud.neptune.community.biz.Utils; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; public class FileUtils { public String ReadFile(String Path) throws IOException{ BufferedReader reader = null; String laststr = ""; try { File f = new File(Path); InputStream fileInputStream = new FileInputStream(f); InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8"); reader = new BufferedReader(inputStreamReader); String tempString = null; while ((tempString = reader.readLine()) != null) { laststr += tempString; } reader.close(); } finally { if (reader != null) { reader.close(); } } return laststr; } }
package com.hikvision.building.cloud.neptune.community.biz.Utils; import java.io.IOException; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; public class JSONUtil { private static Logger logger = LoggerFactory.getLogger(JSONUtil.class); private static ObjectMapper objectMapper = new ObjectMapper(); static { // 排除值为空属性 objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); // 转换成对象时,没有属性的处理,忽略掉 objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); // 进行缩进输出 // configure(SerializationFeature.INDENT_OUTPUT, true); // 进行日期格式化 // if (dateFormatPattern != null) { // DateFormat dateFormat = new SimpleDateFormat(dateFormatPattern); // objectMapper.setDateFormat(dateFormat); // } } /** * 将 POJO 对象转为 JSON 字符串 */ public static <T> String toJson(T pojo) { try { return objectMapper.writeValueAsString(pojo); } catch (Exception e) { logger.error("toJson Failed.", e); throw new RuntimeException("转换json格式异常"); } } /** * 将 JSON 字符串转为 POJO 对象 */ public static <T> T fromJson(String json, Class<T> type) { try { return objectMapper.readValue(json, type); } catch (Exception e) { logger.error("fromJson Failed.", e); throw new RuntimeException("json格式错误" + json); } } /** * JSON串转换为Java泛型对象,可以是各种类型,此方法最为强大。用法看测试用例。 * * @param <T> * @param jsonString * JSON字符串 * @param tr * TypeReference,例如: new TypeReference< List<FamousUser> >(){} * @return List对象列表 */ public static <T> T toCollection(String jsonStr, TypeReference<T> typeReference) { try { return objectMapper.readValue(jsonStr, typeReference); } catch (Exception e) { logger.error("toCollection Failed.", e); throw new RuntimeException("json格式错误" + jsonStr); } } public static Map<?, ?> json2map(String jsonStr) { if (jsonStr == null) { throw new RuntimeException("jsonStr is null"); } try { return objectMapper.readValue(jsonStr, Map.class); } catch (Exception e) { logger.error("json2map Failed.", e); throw new RuntimeException("json格式错误" + jsonStr); } } public static <T> T map2pojo(Map<?, ?> map, Class<T> clazz) { return objectMapper.convertValue(map, clazz); } public static String object2Json(Object obj) { if (obj == null) { logger.error("obj is null."); throw new RuntimeException("入参错误"); } try { return objectMapper.writeValueAsString(obj); } catch (IOException e) { logger.error("object2Json Failed.", e); throw new RuntimeException("转换json格式异常"); } } }