diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..3a8542d --- /dev/null +++ b/.gitignore @@ -0,0 +1,362 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd \ No newline at end of file diff --git a/QNet.CnDistricts.sln b/QNet.CnDistricts.sln new file mode 100644 index 0000000..25f3077 --- /dev/null +++ b/QNet.CnDistricts.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.30330.147 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "QNet.CnDistricts", "QNet.CnDistricts\QNet.CnDistricts.csproj", "{81CF0438-AB82-4CD9-B5FC-C7E6A84CDF37}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {81CF0438-AB82-4CD9-B5FC-C7E6A84CDF37}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {81CF0438-AB82-4CD9-B5FC-C7E6A84CDF37}.Debug|Any CPU.Build.0 = Debug|Any CPU + {81CF0438-AB82-4CD9-B5FC-C7E6A84CDF37}.Release|Any CPU.ActiveCfg = Release|Any CPU + {81CF0438-AB82-4CD9-B5FC-C7E6A84CDF37}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {1DB47CBA-A37E-4485-915D-EDCE14B0B553} + EndGlobalSection +EndGlobal diff --git a/QNet.CnDistricts/Data/Data.cs b/QNet.CnDistricts/Data/Data.cs new file mode 100644 index 0000000..995c47c --- /dev/null +++ b/QNet.CnDistricts/Data/Data.cs @@ -0,0 +1,94 @@ +using System; +using System.Collections.Generic; +using System.Data; +using System.Linq; +using System.Net.WebSockets; +using System.Threading.Tasks; +using MySql.Data.MySqlClient; + +namespace QNet.CnDistricts +{ + public static class Data + { + private const int MaxLevel = 4; // 最高有多少层级 + + // 查询时间复杂度O(1) + private static readonly Dictionary _DicAll = new Dictionary(46473);//总条数 + + // 缓存父子集关系,方便查询 + private static readonly Dictionary _DicPSubset = new Dictionary(); + + private static void LoadFromDb() + { + var strConn = "server=192.168.86.101;port=3306;database=division_cn; uid=root;pwd=123456;charset=utf8mb4"; + using (var conn = new MySqlConnection(strConn)) + { + conn.Open(); + var cmd = new MySqlCommand("SELECT * FROM district", conn); + var dr = cmd.ExecuteReader(); + while (dr.Read()) + { + var district = new District(); + district.Id = dr.GetInt64(0); + district.Pid = dr.GetInt64(1); + district.Name = dr.GetString(2); + + _DicAll.Add(district.Id, district); + } + } + } + + private static void SetDicPSubset(long pid = 0, int level = 1) + { + var subDistricts = _DicAll.Values.Where(x => x.Pid == pid).ToArray(); + + if (subDistricts.Any()) + { + _DicPSubset.Add(pid, subDistricts); + + // 最后一层级没有子集,不要跑递归了,数据多,极其浪费时间~ + if (level < MaxLevel) + { + foreach (var item in subDistricts) + { + SetDicPSubset(item.Id, level + 1); + } + } + + } + } + + public static void Load() + { + LoadFromDb(); + SetDicPSubset(); + } + + public static Dictionary.ValueCollection GetAll() + { + return _DicAll.Values; + } + + public static District[] GetByPid(long pid) + { + District[] districts; + + _DicPSubset.TryGetValue(pid, out districts); + + return districts.ToArray(); + } + + public static List GetById(List ids) + { + var districts = new List(); + foreach (var id in ids) + { + District v; + if (_DicAll.TryGetValue(id, out v)) + districts.Add(v); + } + + return districts; + } + } +} diff --git a/QNet.CnDistricts/Handlers/Common.cs b/QNet.CnDistricts/Handlers/Common.cs new file mode 100644 index 0000000..922934c --- /dev/null +++ b/QNet.CnDistricts/Handlers/Common.cs @@ -0,0 +1,38 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.Json; +using System.Threading.Tasks; + +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Primitives; + +namespace QNet.CnDistricts +{ + public partial class Handler + { + private static readonly JsonSerializerOptions _JsonSerializerOptions; + static Handler() + { + _JsonSerializerOptions = new JsonSerializerOptions(); + _JsonSerializerOptions.Encoder = System.Text.Encodings.Web.JavaScriptEncoder.Create(System.Text.Unicode.UnicodeRanges.All); + } + + private static bool IsLastModifiedExpires(HttpContext context, int expires = 60) + { + var headerValue = context.Request.Headers["If-Modified-Since"]; + if (!StringValues.IsNullOrEmpty(headerValue)) + { + DateTime modifiedSince; + + if (DateTime.TryParse(headerValue.ToString(), out modifiedSince)) + { + return modifiedSince.ToLocalTime().AddSeconds(expires) < DateTime.Now; + } + } + + return true; + + } + } +} diff --git a/QNet.CnDistricts/Handlers/Home.cs b/QNet.CnDistricts/Handlers/Home.cs new file mode 100644 index 0000000..9912259 --- /dev/null +++ b/QNet.CnDistricts/Handlers/Home.cs @@ -0,0 +1,41 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Http; + +namespace QNet.CnDistricts +{ + public partial class Handler + { + public static async Task Home(HttpContext context) + { + if (!IsLastModifiedExpires(context)) + { + context.Response.StatusCode = (int)System.Net.HttpStatusCode.NotModified; + return; + } + + const string html = @" +接口说明 + + +/s +获取所有区域数据 + + +/s?pid= +通过 pid 获取子区域数据 +例如,获取所有省:/s?pid=0 + + +/s?id= +通过 id 获取区域数据,可以用 , 分隔 +例如,获取指定地区数据:/s?id=44,4403,440305 +"; + context.Response.ContentType = "text/plain;charset=UTF-8"; + context.Response.Headers.Add("Last-Modified", DateTime.Now.ToUniversalTime().ToString("R")); + await context.Response.WriteAsync(html); + } + } +} diff --git a/QNet.CnDistricts/Handlers/Search.cs b/QNet.CnDistricts/Handlers/Search.cs new file mode 100644 index 0000000..f825f99 --- /dev/null +++ b/QNet.CnDistricts/Handlers/Search.cs @@ -0,0 +1,72 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.Linq; +using System.Text.Json; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Primitives; + +namespace QNet.CnDistricts +{ + public partial class Handler + { + public static async Task Search(HttpContext context) + { + if (!IsLastModifiedExpires(context)) + { + context.Response.StatusCode = (int)System.Net.HttpStatusCode.NotModified; + return; + } + + + object jsonData = null; + if (context.Request.Query.Count == 0) + { + // 返回所有 + jsonData = Data.GetAll(); + } + else + { + StringValues p; + if (context.Request.Query.TryGetValue("pid", out p)) + { + if (!StringValues.IsNullOrEmpty(p)) + { + long pid; + if (long.TryParse(p.ToString(), out pid)) + { + if (pid > -1) + jsonData = Data.GetByPid(pid); + } + } + } + else if (context.Request.Query.TryGetValue("id", out p)) + { + if (!StringValues.IsNullOrEmpty(p)) + { + var ids = new List(); + foreach (var item in p.ToString().Split(",")) + { + long id; + if (long.TryParse(item, out id)) + { + if (id > 0) + ids.Add(id); + } + } + + if (ids.Any()) + { + jsonData = Data.GetById(ids); + } + } + } + } + + context.Response.ContentType = "application/json;"; + context.Response.Headers.Add("Last-Modified", DateTime.Now.ToUniversalTime().ToString("R")); + await context.Response.BodyWriter.WriteAsync(JsonSerializer.SerializeToUtf8Bytes(jsonData, _JsonSerializerOptions)); + } + } +} diff --git a/QNet.CnDistricts/Models/District.cs b/QNet.CnDistricts/Models/District.cs new file mode 100644 index 0000000..de3fa07 --- /dev/null +++ b/QNet.CnDistricts/Models/District.cs @@ -0,0 +1,16 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace QNet.CnDistricts +{ + public class District + { + public long Id { get; set; } + + public long Pid { get; set; } + + public string Name { get; set; } + } +} diff --git a/QNet.CnDistricts/Program.cs b/QNet.CnDistricts/Program.cs new file mode 100644 index 0000000..db4bc77 --- /dev/null +++ b/QNet.CnDistricts/Program.cs @@ -0,0 +1,26 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; + +namespace QNet.CnDistricts +{ + public class Program + { + public static void Main(string[] args) + { + CreateHostBuilder(args).Build().Run(); + } + + public static IHostBuilder CreateHostBuilder(string[] args) => + Host.CreateDefaultBuilder(args) + .ConfigureWebHostDefaults(webBuilder => + { + webBuilder.UseStartup(); + }); + } +} diff --git a/QNet.CnDistricts/Properties/launchSettings.json b/QNet.CnDistricts/Properties/launchSettings.json new file mode 100644 index 0000000..38d8032 --- /dev/null +++ b/QNet.CnDistricts/Properties/launchSettings.json @@ -0,0 +1,27 @@ +{ + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:54804", + "sslPort": 0 + } + }, + "profiles": { + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "QNet.CnDistricts": { + "commandName": "Project", + "launchBrowser": true, + "applicationUrl": "http://localhost:5000", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/QNet.CnDistricts/QNet.CnDistricts.csproj b/QNet.CnDistricts/QNet.CnDistricts.csproj new file mode 100644 index 0000000..4237e06 --- /dev/null +++ b/QNet.CnDistricts/QNet.CnDistricts.csproj @@ -0,0 +1,11 @@ + + + + netcoreapp3.1 + + + + + + + diff --git a/QNet.CnDistricts/Startup.cs b/QNet.CnDistricts/Startup.cs new file mode 100644 index 0000000..844943a --- /dev/null +++ b/QNet.CnDistricts/Startup.cs @@ -0,0 +1,46 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using Microsoft.Extensions.Hosting; + +namespace QNet.CnDistricts +{ + public class Startup + { + // This method gets called by the runtime. Use this method to add services to the container. + // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 + public void ConfigureServices(IServiceCollection services) + { + } + + // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. + public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IHostApplicationLifetime appLifeTime) + { + if (env.IsDevelopment()) + { + app.UseDeveloperExceptionPage(); + } + + app.UseRouting(); + + app.UseEndpoints(endpoints => + { + endpoints.MapGet("/", Handler.Home); + endpoints.MapGet("/s", Handler.Search); + }); + + + + appLifeTime.ApplicationStarted.Register(() => + { + Data.Load(); + }); + } + } +} diff --git a/QNet.CnDistricts/appsettings.Development.json b/QNet.CnDistricts/appsettings.Development.json new file mode 100644 index 0000000..8983e0f --- /dev/null +++ b/QNet.CnDistricts/appsettings.Development.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft": "Warning", + "Microsoft.Hosting.Lifetime": "Information" + } + } +} diff --git a/QNet.CnDistricts/appsettings.json b/QNet.CnDistricts/appsettings.json new file mode 100644 index 0000000..d9d9a9b --- /dev/null +++ b/QNet.CnDistricts/appsettings.json @@ -0,0 +1,10 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft": "Warning", + "Microsoft.Hosting.Lifetime": "Information" + } + }, + "AllowedHosts": "*" +} diff --git a/README.md b/README.md new file mode 100644 index 0000000..0b7c38e --- /dev/null +++ b/README.md @@ -0,0 +1,37 @@ +# 中国省市区街道四级联动 + +## 目标 + +很多项目需要在填写地址中选省市区,本项目希望成为众多项目中的一个微服务~ + + +## Web 框架选择 + +按:https://www.techempower.com/benchmarks 2020-05-28 的 Round 19 中 + +`Fortunes` 的权重比 `Plaintext` 高,因为 `Fortunes` 是一种更现实的测试类型, +但本项目业务极其简单,基本上只是查询,一年中也不会有几次修改,所以选择 `Plaintext(代表响应性能)` 第一的 Asp.Net Core 框架~ + + + +## 数据来源 + +https://github.com/modood/Administrative-divisions-of-China + +创建数据库,创建表 **district** + +| 字段 | 类型 | 是否是主键 | 注释 | +| ---- | --------------------- | ---------- | ------------ | +| id | bigint NOT NULL | 是 | 地区编码 | +| pid | bigint NOT NULL | 否 | 上级地区编码 | +| name | varchar(255) NOT NULL | 否 | 地区名称 | + + +``` sql +CREATE TABLE `district_cn`.`district` ( + `id` bigint NOT NULL COMMENT '地区编码', + `pid` bigint NOT NULL COMMENT '上级地区编码', + `name` varchar(255) NOT NULL COMMENT '地区名称', + PRIMARY KEY (`Id`) +); +``` \ No newline at end of file