省市区(输入code) 转相应省市区工具类(两种方式)

 方式一 通过调用接口(时间高达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) { // success
                BufferedReader 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 code
        String parsedData = getAndParseRegionData(regionCode);
        System.out.println(parsedData);
    }
}

 运行之后代码

ca4b123ad6844e3ab5eac4579fb2e59c.png

261ab19811ea415185022e884d1a61ee.png

5d812d99c74f4f258714caca61e5807c.png

方式二 通过读文件 存入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;

    @Bean
    public 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 的键

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @PostConstruct
    public 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 {
    @Autowired
    private 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);
    }

    // 获取地区对应的 code
    public String getCodeByLocation(String location) {
        HashOperations<String, String, String> hashOps = redisTemplate.opsForHash();
        return hashOps.get(LOCATION_TO_CODE_KEY, location);
    }
}

测试


@SpringBootTest
public class demo {

    @Resource
    private LocationUtil locationUtil;
    @Test
    public void test1()
    {
        String location = locationUtil.getCodeByLocation("东城区");
        System.out.println(location);
        String locationByCode = locationUtil.getLocationByCode("710001");
        System.out.println(locationByCode);

    }
}

8da6fa36ed9a459ba14d2c708133a718.png

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

humannoid

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值