省市區(輸入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) { // 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);}
}

?運行之后代碼

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;@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);}
}

8da6fa36ed9a459ba14d2c708133a718.png

?

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/web/16147.shtml
繁體地址,請注明出處:http://hk.pswp.cn/web/16147.shtml
英文地址,請注明出處:http://en.pswp.cn/web/16147.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

Java 泛型基礎

目錄 1. 為什么使用泛型 2. 泛型的使用方式 2.1. 泛型類 2.2. 泛型接口 2.3. 泛型方法 3. 泛型涉及的符號 3.1. 類型通配符"?" 3.2. 占位符 T/K/V/E 3.3. 占位符T和通配符&#xff1f;的區別。 4. 泛型不變性 5. 泛型編譯時擦除 1. 為什么使用泛型 Java 為…

基于深度學習的入侵檢測系統綜述文獻概述

好長時間不發博客了&#xff0c;不是因為我擺爛了&#xff0c;是我換研究方向了&#xff0c;以后我就要搞科研了。使用博客記錄我的科研故事&#xff0c;邀諸君共同見證我的科研之路。 1、研究方向的背景是什么&#xff1f; &#xff08;1&#xff09;互聯網發展迅速&#xff…

Android firebase消息推送集成 FCM消息處理

FirebaseMessagingService 是 Firebase Cloud Messaging (FCM) 提供的一個服務&#xff0c;用于處理來自 Firebase 服務器的消息。它有幾個關鍵的方法&#xff0c;你提到的 onMessageReceived、doRemoteMessage 和 handleIntent 各有不同的用途。下面逐一解釋這些方法的作用和用…

在 C++ 中,p->name 和 p.name 的效果并不相同。它們用于不同的情況,取決于你是否通過指針訪問結構體成員。

p->name&#xff1a;這是指針訪問運算符&#xff08;箭頭運算符&#xff09;。當 p 是一個指向結構體的指針時&#xff0c;用 p->name 來訪問結構體的成員。 student* p &stu; // p 是一個指向 student 類型的指針 cout << p->name << endl; // 通過…

基于ssm的蛋糕商城系統java項目jsp項目javaweb

文章目錄 蛋糕商城系統一、項目演示二、項目介紹三、系統部分功能截圖四、部分代碼展示五、底部獲取項目源碼&#xff08;9.9&#xffe5;帶走&#xff09; 蛋糕商城系統 一、項目演示 蛋糕商城管理系統 二、項目介紹 系統角色 : 管理員、用戶 一&#xff0c;管理員 管理員有…

PICO VR眼鏡定制播放器使用說明文檔videoplayerlib-ToB.apk

安裝高級定制播放器 高級定制播放器下載地址:https://download.csdn.net/download/ahphong/89360454 僅限用于PICO G2、G3、G4、NEO系列VR眼鏡上使用, 用途:用于第三方APP(開發者)調用定制播放器播放2D、3D、180、360全景視頻。 VR眼鏡系統請升級到最新版,可在官網下載,…

Mixed-precision計算原理(FP32+FP16)

原文&#xff1a; https://lightning.ai/pages/community/tutorial/accelerating-large-language-models-with-mixed-precision-techniques/ This approach allows for efficient training while maintaining the accuracy and stability of the neural network. In more det…

【排序算法】選擇排序以及需要注意的問題

選擇排序的基本思想&#xff1a;每一次從待排序的數據元素中選出最小&#xff08;或最大&#xff09;的一個元素&#xff0c;存放在序列的起始位置&#xff0c;直到全部待排序的數據元素排完 。 第一種實現方法&#xff1a; void SelectSort(int* arr, int n) {for (int j 0…

【kubernetes】探索k8s集群中金絲雀發布后續 + 聲明式資源管理yaml

目錄 一、K8S常見的發布方式 1.1藍綠發布 1.2灰度發布&#xff08;金絲雀發布&#xff09; 1.3滾動發布 二、金絲雀發布 三、聲明式管理方法 3.1YAML 語法格式 3.1.1查看 api 資源版本標簽 3.1.2查看資源簡寫 3.2YAML文件詳解 3.2.1Deployment.yaml 3.2.2Pod.yaml …

CSS3特殊屬性

特殊屬性 will-change will-change 屬性用于向瀏覽器提供提示,表明某個元素或其特定屬性在未來極有可能發生變化。這有助于瀏覽器提前優化相關渲染流程,提升動畫或其他動態效果的性能。 element {will-change: auto | <animateable-feature> [, <animateable-feat…

C++系列-C/C++內存管理方式

&#x1f308;個人主頁&#xff1a;羽晨同學 &#x1f4ab;個人格言:“成為自己未來的主人~” C/C內存分布 在這篇文章開始之前&#xff0c;我們先以一道題目來進行引入&#xff1a; int glovalvar 1; static int staticGlovalvar 1; void Test() {static int staticva…

Java進階學習筆記27——StringBuilder、StringBuffer

StringBuilder&#xff1a; StringBuilder代表可變字符串對象&#xff0c;相當于一個容器&#xff0c;它里面裝的字符串是可以改變的&#xff0c;就是用來操作字符串的。 好處&#xff1a; StringBuilder比String更適合做字符串的修改操作&#xff0c;效率會更高&#xff0c;…

在CSDN上成長的感悟,你的粉絲長啥樣?

文章目錄 一、寫作的初衷1. 記錄所學內容2.鞏固所學知識3.分享與幫助4.方便后續查找5.獲取激勵 二、你的粉絲長啥樣&#xff1f;1. 粉絲的特點與困惑2. 關于粉絲&#xff0c;細思極恐 三、繼續前行、堅持初心 在CSDN上寫博文&#xff0c;對于我來說&#xff0c;不僅僅是一個記錄…

OTA在線旅行社系統架構:連接世界的科技紐帶

隨著互聯網的快速發展和人們對旅行需求的不斷增長&#xff0c;OTA&#xff08;Online Travel Agency&#xff09;在線旅行社成為了現代旅行業中的重要一環。OTA系統架構的設計和實現將對旅行行業產生深遠影響。本文將探討OTA在線旅行社系統架構的重要性和關鍵組成部分&#xff…

異構圖上的連接預測一

這里寫目錄標題 異構圖&#xff1f;處理數據&#xff1a; 異構圖&#xff1f; 異構圖&#xff1a;就是指節點與邊類型不同的圖。 連接預測&#xff1a;目的是預測圖中兩個節點之間是否存在一條邊&#xff0c;或者是預測兩個節點之間&#xff0c;在未來可能形成的連接。 eg&…

Linux系統如何通過編譯方式安裝python3.11.3

1.切換到/data 目錄 cd /data 2.下載python源碼Python-3.11.3.tgz wget https://www.python.org/ftp/python/3.11.3/Python-3.11.3.tgz tar -xzf Python-3.11.0.tgz cd Python-3.11.3 3.配置python的安裝路徑 和 執行openssl的路徑 ./configure --prefix/usr/local/pyth…

Java筑基(三)

Java筑基&#xff08;三&#xff09; 一、final概念1、案例1&#xff1a;采用繼承&#xff1a;2、案例2&#xff1a;final修飾的類不可以被繼承&#xff1a;3、案例3&#xff1a;final修飾的類不能有子類&#xff0c;但是可以有父類4、final修飾構造方法5、final修飾普通方法6、…

頭歌GCC編程工具集第1關:實驗工具GCC與objdump的使用

任務要求 根據提示&#xff0c;在右側編輯器中顯示的bytes.c文件中的 Begin-End 之間補充代碼&#xff08;即設置一個數組的初始值&#xff09;&#xff0c;使其與如下顯示的main.c文件一起編譯、生成的程序在運行時輸出“SUCCESS”。 程序源文件main.c的內容如下&#xff08;務…

牛客前端面試高頻八股總結(1)(附文檔)

1.html語義化 要求使用具有語義的標簽&#xff1a;header footer article aside section nav 三點好處&#xff1a; &#xff08;1&#xff09;提高代碼可讀性&#xff0c;頁面內容結構化&#xff0c;更清晰 &#xff08;2&#xff09;無css時&#xff0c;時頁面呈現出良好…

滲透工具CobaltStrike工具的下載和安裝

一、CobalStrike簡介 Cobalt Strike(簡稱為CS)是一款基于java的滲透測試工具&#xff0c;專業的團隊作戰的滲透測試工具。CS使用了C/S架構&#xff0c;它分為客戶端(Client)和服務端(Server)&#xff0c;服務端只要一個&#xff0c;客戶端可有多個&#xff0c;多人連接服務端后…