省市区(输入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.mzph.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;多人连接服务端后…