方式一 通过调用接口(时间高达1s)
package cn.iocoder.yudao.module.supplier.utils;import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;/**** 区域划分代码工具类 只需要传 相应代码值 就会返回 对应区域*/
public class AdministrativeRegionUtil {private static final String BASE_URL = "https://xingzhengquhua.bmcx.com/";public static String getAdministrativeRegionData(String regionCode) {regionCode = padRegionCode(regionCode);String urlString = BASE_URL + regionCode + "__xingzhengquhua/";StringBuilder result = new StringBuilder();try {URL url = new URL(urlString);HttpURLConnection conn = (HttpURLConnection) url.openConnection();conn.setRequestMethod("GET");int responseCode = conn.getResponseCode();if (responseCode == HttpURLConnection.HTTP_OK) { // successBufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));String inputLine;while ((inputLine = in.readLine()) != null) {result.append(inputLine);}in.close();} else {System.out.println("GET request not worked");}} catch (Exception e) {e.printStackTrace();}return result.toString();}public static String padRegionCode(String regionCode) {if (regionCode == null) {throw new IllegalArgumentException("Region code cannot be null");}return String.format("%-12s", regionCode).replace(' ', '0');}public static String parseRegionData(String html) {Document doc = Jsoup.parse(html);Element h3Element = doc.selectFirst("td:contains(行政区划代码) h3");Element spanElement = doc.selectFirst("td:contains(行政区划代码) span");if (h3Element != null && spanElement != null) {String regionName = h3Element.text();String regionCode = spanElement.text();return "RegionName: " + regionName + ", RegionCode: " + regionCode;}return "Data not found";}public static String getAndParseRegionData(String regionCode) {String htmlData = getAdministrativeRegionData(regionCode);return parseRegionData(htmlData);}public static void main(String[] args) {String regionCode = "650000"; // Example region codeString parsedData = getAndParseRegionData(regionCode);System.out.println(parsedData);}
}
运行之后代码
方式二 通过读文件 存入redis缓存中
文件格式举例
推荐一个文本格式化网站 中英文自动加空格 - 小牛知识库 (xnip.cn)
110000 北京市
110101 东城区
110102 西城区
110105 朝阳区
110106 丰台区
110107 石景山区
110108 海淀区
110109 门头沟区
110111 房山区
110112 通州区
110113 顺义区
110114 昌平区
110115 大兴区
代码
配置类
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;@Configuration
public class RedisConfig {@Value("${spring.redis.host}")private String host;@Value("${spring.redis.port}")private int port;@Value("${spring.redis.database}")private int database;@Beanpublic RedisConnectionFactory redisConnectionFactory() {RedisStandaloneConfiguration config = new RedisStandaloneConfiguration(host, port);config.setDatabase(database);return new LettuceConnectionFactory(config);}
}
读取文件到redis的工具类
package cn.iocoder.yudao.module.supplier.utils;import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;import javax.annotation.PostConstruct;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;import org.springframework.data.redis.core.HashOperations;/**** 地区工具类 自动注入redis**/
@Component
@Slf4j
public class RedisDataLoader {private static final String FILE_PATH = "yudao-module-supplier/yudao-module-supplier-biz/src/main/java/cn/iocoder/yudao/module/supplier/utils/file/locateFile.txt"; // 替换为你的文件路径private static final String CODE_TO_LOCATION_KEY = "LocationByCode"; // Redis Hash 的键private static final String LOCATION_TO_CODE_KEY = "CodeByLocation"; // Redis Hash 的键@Autowiredprivate RedisTemplate<String, String> redisTemplate;@PostConstructpublic void loadFileToRedis() {// 读取文件行数,用于检查是否拥有所有数据int expectedDataCount = countLines(FILE_PATH);// 查询 Redis 中已有数据的数量long existingDataCount = redisTemplate.opsForHash().size(CODE_TO_LOCATION_KEY);// 如果 Redis 中数据不足预期数量,则继续加载数据if (existingDataCount < expectedDataCount) {try (BufferedReader br = new BufferedReader(new FileReader(FILE_PATH))) {String line;HashOperations<String, String, String> codeToLocationHashOps = redisTemplate.opsForHash();HashOperations<String, String, String> locationToCodeHashOps = redisTemplate.opsForHash();int count = 0; // 计数器while ((line = br.readLine()) != null) {String[] parts = line.trim().split("\\s+", 2); // 使用空格字符分割,限制为两部分if (parts.length == 2) {String code = parts[0].trim(); // 第一部分作为区域代码String location = parts[1].trim(); // 第二部分作为地区名称codeToLocationHashOps.put(CODE_TO_LOCATION_KEY, code, location);locationToCodeHashOps.put(LOCATION_TO_CODE_KEY, location, code);count++; // 每存储一条数据,计数器加一}}log.info("存在地区数据{}条",count);} catch (IOException e) {e.printStackTrace();}} else {log.info("地区数据已缓存 无需加载");}}// 获取文件行数,用于检查是否拥有所有数据private int countLines(String filePath) {int count = 0;try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {while (reader.readLine() != null) count++;} catch (IOException e) {e.printStackTrace();}return count;}}
通过code码获取对应地点名称 及相反 工具类
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;@Component
public class LocationUtil {@Autowiredprivate RedisTemplate<String, String> redisTemplate;private static final String CODE_TO_LOCATION_KEY = "LocationByCode"; // Redis Hash 的键private static final String LOCATION_TO_CODE_KEY = "CodeByLocation"; // Redis Hash 的键// 获取 code 对应的地区public String getLocationByCode(String code) {HashOperations<String, String, String> hashOps = redisTemplate.opsForHash();return hashOps.get(CODE_TO_LOCATION_KEY, code);}// 获取地区对应的 codepublic String getCodeByLocation(String location) {HashOperations<String, String, String> hashOps = redisTemplate.opsForHash();return hashOps.get(LOCATION_TO_CODE_KEY, location);}
}
测试
@SpringBootTest
public class demo {@Resourceprivate LocationUtil locationUtil;@Testpublic void test1(){String location = locationUtil.getCodeByLocation("东城区");System.out.println(location);String locationByCode = locationUtil.getLocationByCode("710001");System.out.println(locationByCode);}
}