├── src ├── .vs │ └── CanalSharp.AspNetCore │ │ └── v15 │ │ └── Server │ │ └── sqlite3 │ │ └── db.lock ├── Infrastructure │ ├── Enums │ │ └── CanalEnums.cs │ ├── Options │ │ ├── MySqlOutputOptions.cs │ │ ├── MongoOutputOptions.cs │ │ └── OutputOptions.cs │ ├── Repositories │ │ ├── ICanalRepository.cs │ │ ├── MongoDB │ │ │ ├── MongoDbContext.cs │ │ │ ├── CanalLogDbContext.cs │ │ │ └── MongoCanalRepository.cs │ │ ├── CanalRepositoryFactory.cs │ │ └── MySql │ │ │ └── MySqlCanalRepository.cs │ └── Models │ │ └── ChangeLog.cs ├── CanalSharp │ ├── ICanalClientHandler.cs │ ├── CanalOption.cs │ └── CanalClientHandler.cs ├── CanalSharp.AspNetCore.csproj ├── Utils │ └── DateConvertUtil.cs ├── CanalSharp.AspNetCore.sln └── Extensions │ └── CanalAppBuilderExtensions.cs ├── sample ├── appsettings.json ├── appsettings.Development.json ├── Properties │ └── launchSettings.json ├── Program.cs ├── CanalSharp.AspNetCore.Sample.csproj ├── CanalSharp.AspNetCore.Sample.sln └── Startup.cs ├── LICENSE ├── .gitignore └── README.md /src/.vs/CanalSharp.AspNetCore/v15/Server/sqlite3/db.lock: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /sample/appsettings.json: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EdisonTalk/CanalSharp.AspNetCore/HEAD/sample/appsettings.json -------------------------------------------------------------------------------- /src/Infrastructure/Enums/CanalEnums.cs: -------------------------------------------------------------------------------- 1 | namespace CanalSharp.AspNetCore.Infrastructure.Enums 2 | { 3 | public enum OutputEnum 4 | { 5 | MySql = 0, 6 | Mongo = 1 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /sample/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Debug", 5 | "System": "Information", 6 | "Microsoft": "Information" 7 | } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/Infrastructure/Options/MySqlOutputOptions.cs: -------------------------------------------------------------------------------- 1 | namespace CanalSharp.AspNetCore.Infrastructure 2 | { 3 | public class MySqlOutputOptions: OutputOptions 4 | { 5 | public string ConnectionString { get; set; } 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /src/CanalSharp/ICanalClientHandler.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace CanalSharp.AspNetCore.CanalSharp 4 | { 5 | public interface ICanalClientHandler : IDisposable 6 | { 7 | void Initialize(); 8 | 9 | void Start(); 10 | 11 | void Stop(); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/Infrastructure/Options/MongoOutputOptions.cs: -------------------------------------------------------------------------------- 1 | namespace CanalSharp.AspNetCore.Infrastructure 2 | { 3 | public class MongoOutputOptions : OutputOptions 4 | { 5 | public string ConnectionString { get; set; } 6 | 7 | public string DataBase { get; set; } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/Infrastructure/Repositories/ICanalRepository.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Threading.Tasks; 3 | 4 | namespace CanalSharp.AspNetCore.Infrastructure 5 | { 6 | public interface ICanalRepository 7 | { 8 | Task InitializeAsync(); 9 | 10 | Task SaveChangeHistoriesAsync(List changeHistories); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /sample/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "http://json.schemastore.org/launchsettings.json", 3 | "profiles": { 4 | "CanalSharp.AspNetCore.Sample": { 5 | "commandName": "Project", 6 | "launchBrowser": false, 7 | "applicationUrl": "http://localhost:8000", 8 | "environmentVariables": { 9 | "ASPNETCORE_ENVIRONMENT": "Development" 10 | } 11 | } 12 | } 13 | } -------------------------------------------------------------------------------- /sample/Program.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore; 2 | using Microsoft.AspNetCore.Hosting; 3 | 4 | namespace CanalSharp.AspNetCore.Sample 5 | { 6 | public class Program 7 | { 8 | public static void Main(string[] args) 9 | { 10 | CreateWebHostBuilder(args).Build().Run(); 11 | } 12 | 13 | public static IWebHostBuilder CreateWebHostBuilder(string[] args) => 14 | WebHost.CreateDefaultBuilder(args) 15 | .UseStartup(); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/Infrastructure/Repositories/MongoDB/MongoDbContext.cs: -------------------------------------------------------------------------------- 1 | using MongoDB.Driver; 2 | 3 | namespace CanalSharp.AspNetCore.Infrastructure 4 | { 5 | public class MongoDbContext 6 | { 7 | protected readonly IMongoClient mongoClient; 8 | protected readonly IMongoDatabase mongoDatabase; 9 | 10 | public MongoDbContext(MongoOutputOptions outputOptions) 11 | { 12 | mongoClient = new MongoClient(outputOptions.ConnectionString); 13 | mongoDatabase = mongoClient.GetDatabase(outputOptions.DataBase); 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/Infrastructure/Repositories/MongoDB/CanalLogDbContext.cs: -------------------------------------------------------------------------------- 1 | using MongoDB.Driver; 2 | 3 | namespace CanalSharp.AspNetCore.Infrastructure 4 | { 5 | public class CanalLogDbContext: MongoDbContext 6 | { 7 | public CanalLogDbContext(MongoOutputOptions outputOptions) 8 | : base(outputOptions) 9 | { 10 | } 11 | 12 | public IMongoCollection ChangeLogs 13 | { 14 | get 15 | { 16 | return mongoDatabase.GetCollection("changelogs"); 17 | } 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/Infrastructure/Models/ChangeLog.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace CanalSharp.AspNetCore.Infrastructure 4 | { 5 | public class ChangeLog 6 | { 7 | public string Id { get; set; } = Guid.NewGuid().ToString(); 8 | 9 | public string SchemaName { get; set; } 10 | 11 | public string TableName { get; set; } 12 | 13 | public string EventType { get; set; } 14 | 15 | public string ColumnName { get; set; } 16 | 17 | public string PreviousValue { get; set; } 18 | 19 | public string CurrentValue { get; set; } 20 | 21 | public DateTime ExecuteTime { get; set; } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/Infrastructure/Options/OutputOptions.cs: -------------------------------------------------------------------------------- 1 | using CanalSharp.AspNetCore.Infrastructure.Enums; 2 | 3 | namespace CanalSharp.AspNetCore.Infrastructure 4 | { 5 | public class OutputOptions 6 | { 7 | public const string DefaultSchema = "canal"; 8 | public const string DefaultTableName = "logs"; 9 | public const OutputEnum DefaultOutput = OutputEnum.MySql; 10 | 11 | public virtual string TableNamePrefix { get; set; } = DefaultSchema; 12 | 13 | public virtual string TableName { get; set; } = DefaultTableName; 14 | 15 | public virtual OutputEnum Output { get; set; } = DefaultOutput; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /sample/CanalSharp.AspNetCore.Sample.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp3.1 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /src/CanalSharp/CanalOption.cs: -------------------------------------------------------------------------------- 1 | using CanalSharp.AspNetCore.Infrastructure.Enums; 2 | 3 | namespace CanalSharp.AspNetCore.CanalSharp 4 | { 5 | public class CanalOption 6 | { 7 | public string CanalServerIP { get; set; } 8 | 9 | public int CanalServerPort { get; set; } 10 | 11 | public string Destination { get; set; } 12 | 13 | public string UserName { get; set; } 14 | 15 | public string Password { get; set; } 16 | 17 | public string Filter { get; set; } 18 | 19 | public int SleepTime { get; set; } 20 | 21 | public int BufferSize { get; set; } 22 | 23 | public string LogSource { get; set; } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/Infrastructure/Repositories/CanalRepositoryFactory.cs: -------------------------------------------------------------------------------- 1 | using CanalSharp.AspNetCore.Infrastructure.Enums; 2 | 3 | namespace CanalSharp.AspNetCore.Infrastructure 4 | { 5 | public static class CanalRepositoryFactory 6 | { 7 | public static ICanalRepository GetCanalRepositoryInstance(OutputOptions options) 8 | { 9 | ICanalRepository canalRepository = null; 10 | 11 | switch (options.Output) 12 | { 13 | case OutputEnum.MySql: 14 | canalRepository = new MySqlCanalRepository(options as MySqlOutputOptions); 15 | break; 16 | case OutputEnum.Mongo: 17 | canalRepository = new MongoCanalRepository(options as MongoOutputOptions); 18 | break; 19 | } 20 | 21 | return canalRepository; 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/Infrastructure/Repositories/MongoDB/MongoCanalRepository.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Threading.Tasks; 3 | 4 | namespace CanalSharp.AspNetCore.Infrastructure 5 | { 6 | public class MongoCanalRepository : ICanalRepository 7 | { 8 | private readonly MongoOutputOptions _options; 9 | private readonly CanalLogDbContext _logDbContext; 10 | 11 | public MongoCanalRepository(MongoOutputOptions options) 12 | { 13 | _options = options; 14 | _logDbContext = new CanalLogDbContext(_options); 15 | } 16 | 17 | public async Task InitializeAsync() 18 | { 19 | await Task.CompletedTask; 20 | } 21 | 22 | public async Task SaveChangeHistoriesAsync(List changeHistories) 23 | { 24 | await _logDbContext.ChangeLogs.InsertManyAsync(changeHistories); 25 | return true; 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/CanalSharp.AspNetCore.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp3.1 5 | Edison Zhou 6 | One component for ASP.NET Core based on open source Canal Client - CanalSharp 7 | Copyright © 2020 Edison Zhou 8 | true 9 | 0.0.7 10 | 11 | https://github.com/XiLife-OSPC/CanalSharp.AspNetCore 12 | XiLife-OSPC 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /src/Utils/DateConvertUtil.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace CanalSharp.AspNetCore.Utils 4 | { 5 | /// 6 | /// 日期格式帮助类 7 | /// 支持日期与时间戳格式的互相转换 8 | /// 9 | public static class DateConvertUtil 10 | { 11 | /// 12 | /// 时间戳转为C#格式时间 13 | /// 14 | /// Unix时间戳格式 15 | /// C#格式时间 16 | public static DateTime ToDateTime(long timeStamp) 17 | { 18 | DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)); 19 | long time = timeStamp * 10000; 20 | TimeSpan toNow = new TimeSpan(time); 21 | 22 | return dtStart.Add(toNow); 23 | } 24 | 25 | /// 26 | /// DateTime时间格式转换为Unix时间戳格式 27 | /// 28 | /// DateTime时间格式 29 | /// Long型Unix时间戳格式 30 | public static long ToTimeStamp(DateTime time) 31 | { 32 | DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)); 33 | return (long)(time - startTime).TotalMilliseconds; 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /sample/CanalSharp.AspNetCore.Sample.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 15 4 | VisualStudioVersion = 15.0.28010.2050 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CanalSharp.AspNetCore.Sample", "CanalSharp.AspNetCore.Sample.csproj", "{790C07B6-6B09-4A53-9E1A-C60DD70CB701}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Release|Any CPU = Release|Any CPU 12 | EndGlobalSection 13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 14 | {790C07B6-6B09-4A53-9E1A-C60DD70CB701}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {790C07B6-6B09-4A53-9E1A-C60DD70CB701}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {790C07B6-6B09-4A53-9E1A-C60DD70CB701}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {790C07B6-6B09-4A53-9E1A-C60DD70CB701}.Release|Any CPU.Build.0 = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | GlobalSection(ExtensibilityGlobals) = postSolution 23 | SolutionGuid = {5E2BDDD2-DE55-42BD-A829-66C609CB104B} 24 | EndGlobalSection 25 | EndGlobal 26 | -------------------------------------------------------------------------------- /sample/Startup.cs: -------------------------------------------------------------------------------- 1 | using CanalSharp.AspNetCore.Extensions; 2 | using Microsoft.AspNetCore.Builder; 3 | using Microsoft.AspNetCore.Hosting; 4 | using Microsoft.AspNetCore.Mvc; 5 | using Microsoft.Extensions.Configuration; 6 | using Microsoft.Extensions.DependencyInjection; 7 | 8 | namespace CanalSharp.AspNetCore.Sample 9 | { 10 | public class Startup 11 | { 12 | public Startup(IConfiguration configuration) 13 | { 14 | Configuration = configuration; 15 | } 16 | 17 | public IConfiguration Configuration { get; } 18 | 19 | // This method gets called by the runtime. Use this method to add services to the container. 20 | public void ConfigureServices(IServiceCollection services) 21 | { 22 | services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0); 23 | } 24 | 25 | // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 26 | public void Configure(IApplicationBuilder app, IHostingEnvironment env) 27 | { 28 | if (env.IsDevelopment()) 29 | { 30 | app.UseDeveloperExceptionPage(); 31 | } 32 | 33 | app.UseCanalClient(Configuration); 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/CanalSharp.AspNetCore.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 15 4 | VisualStudioVersion = 15.0.28010.2050 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CanalSharp.AspNetCore", "CanalSharp.AspNetCore.csproj", "{F500CE2E-CA2C-4A6F-A89C-B5A2D6763405}" 7 | EndProject 8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CanalSharp.AspNetCore.Sample", "..\sample\CanalSharp.AspNetCore.Sample.csproj", "{87A374B6-78EA-43D6-B3DF-943343C63230}" 9 | EndProject 10 | Global 11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 12 | Debug|Any CPU = Debug|Any CPU 13 | Release|Any CPU = Release|Any CPU 14 | EndGlobalSection 15 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 16 | {F500CE2E-CA2C-4A6F-A89C-B5A2D6763405}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 17 | {F500CE2E-CA2C-4A6F-A89C-B5A2D6763405}.Debug|Any CPU.Build.0 = Debug|Any CPU 18 | {F500CE2E-CA2C-4A6F-A89C-B5A2D6763405}.Release|Any CPU.ActiveCfg = Release|Any CPU 19 | {F500CE2E-CA2C-4A6F-A89C-B5A2D6763405}.Release|Any CPU.Build.0 = Release|Any CPU 20 | {87A374B6-78EA-43D6-B3DF-943343C63230}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 21 | {87A374B6-78EA-43D6-B3DF-943343C63230}.Debug|Any CPU.Build.0 = Debug|Any CPU 22 | {87A374B6-78EA-43D6-B3DF-943343C63230}.Release|Any CPU.ActiveCfg = Release|Any CPU 23 | {87A374B6-78EA-43D6-B3DF-943343C63230}.Release|Any CPU.Build.0 = Release|Any CPU 24 | EndGlobalSection 25 | GlobalSection(SolutionProperties) = preSolution 26 | HideSolutionNode = FALSE 27 | EndGlobalSection 28 | GlobalSection(ExtensibilityGlobals) = postSolution 29 | SolutionGuid = {3636BE21-2284-462F-B837-99442CC32B22} 30 | EndGlobalSection 31 | EndGlobal 32 | -------------------------------------------------------------------------------- /src/Infrastructure/Repositories/MySql/MySqlCanalRepository.cs: -------------------------------------------------------------------------------- 1 | using MySql.Data.MySqlClient; 2 | using System.Collections.Generic; 3 | using System.Threading.Tasks; 4 | using Dapper; 5 | 6 | namespace CanalSharp.AspNetCore.Infrastructure 7 | { 8 | public class MySqlCanalRepository : ICanalRepository 9 | { 10 | private readonly MySqlOutputOptions _options; 11 | 12 | public MySqlCanalRepository(MySqlOutputOptions options) 13 | { 14 | _options = options; 15 | } 16 | 17 | public async Task InitializeAsync() 18 | { 19 | var ddlSql = 20 | $@" 21 | CREATE TABLE IF NOT EXISTS `{_options.TableNamePrefix}.{_options.TableName}` ( 22 | `Id` varchar(128) NOT NULL COMMENT 'Id', 23 | `SchemaName` varchar(50) DEFAULT NULL COMMENT '数据库名称', 24 | `TableName` varchar(50) DEFAULT NULL COMMENT '表名', 25 | `EventType` varchar(50) DEFAULT NULL COMMENT '事件类型', 26 | `ColumnName` varchar(50) DEFAULT NULL COMMENT '列名', 27 | `PreviousValue` text COMMENT '变更前的值', 28 | `CurrentValue` text COMMENT '变更后的值', 29 | `ExecuteTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP COMMENT '变更时间', 30 | PRIMARY KEY (`Id`) 31 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='变更日志记录表';"; 32 | 33 | using (var conn = new MySqlConnection((_options as MySqlOutputOptions).ConnectionString)) 34 | { 35 | await conn.ExecuteAsync(ddlSql); 36 | } 37 | } 38 | 39 | public async Task SaveChangeHistoriesAsync(List changeHistories) 40 | { 41 | if (changeHistories == null || changeHistories.Count == 0) 42 | { 43 | return true; 44 | } 45 | 46 | using (var conn = new MySqlConnection(_options.ConnectionString)) 47 | { 48 | var sql = $@"INSERT INTO `{_options.TableNamePrefix}.{_options.TableName}` 49 | (`Id`,`SchemaName`,`TableName`,`EventType`,`ColumnName`,`PreviousValue`,`CurrentValue`,`ExecuteTime`) 50 | VALUES(@Id, @SchemaName, @TableName, @EventType, @ColumnName, @PreviousValue, @CurrentValue, @ExecuteTime)"; 51 | return await conn.ExecuteAsync(sql, changeHistories) > 0; 52 | } 53 | } 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # ---> C Sharp 2 | # Build Folders (you can keep bin if you'd like, to store dlls and pdbs) 3 | [Bb]in/ 4 | [Oo]bj/ 5 | 6 | # mstest test results 7 | TestResults 8 | 9 | ## Ignore Visual Studio temporary files, build results, and 10 | ## files generated by popular Visual Studio add-ons. 11 | 12 | # User-specific files 13 | *.suo 14 | *.user 15 | *.sln.docstates 16 | 17 | # Build results 18 | [Dd]ebug/ 19 | [Rr]elease/ 20 | x64/ 21 | *_i.c 22 | *_p.c 23 | *.ilk 24 | *.meta 25 | *.obj 26 | *.pch 27 | *.pdb 28 | *.pgc 29 | *.pgd 30 | *.rsp 31 | *.sbr 32 | *.tlb 33 | *.tli 34 | *.tlh 35 | *.tmp 36 | *.log 37 | *.vspscc 38 | *.vssscc 39 | .builds 40 | 41 | # Visual C++ cache files 42 | ipch/ 43 | *.aps 44 | *.ncb 45 | *.opensdf 46 | *.sdf 47 | 48 | # Visual Studio profiler 49 | *.psess 50 | *.vsp 51 | *.vspx 52 | 53 | # Guidance Automation Toolkit 54 | *.gpState 55 | 56 | # ReSharper is a .NET coding add-in 57 | _ReSharper* 58 | 59 | # NCrunch 60 | *.ncrunch* 61 | .*crunch*.local.xml 62 | 63 | # Installshield output folder 64 | [Ee]xpress 65 | 66 | # DocProject is a documentation generator add-in 67 | DocProject/buildhelp/ 68 | DocProject/Help/*.HxT 69 | DocProject/Help/*.HxC 70 | DocProject/Help/*.hhc 71 | DocProject/Help/*.hhk 72 | DocProject/Help/*.hhp 73 | DocProject/Help/Html2 74 | DocProject/Help/html 75 | 76 | # Click-Once directory 77 | publish 78 | 79 | # Publish Web Output 80 | *.Publish.xml 81 | 82 | # NuGet Packages Directory 83 | packages 84 | 85 | # Windows Azure Build Output 86 | csx 87 | *.build.csdef 88 | 89 | # Windows Store app package directory 90 | AppPackages/ 91 | 92 | # Others 93 | [Bb]in 94 | [Oo]bj 95 | sql 96 | TestResults 97 | [Tt]est[Rr]esult* 98 | *.Cache 99 | ClientBin 100 | [Ss]tyle[Cc]op.* 101 | ~$* 102 | *.dbmdl 103 | Generated_Code #added for RIA/Silverlight projects 104 | 105 | # Backup & report files from converting an old project file to a newer 106 | # Visual Studio version. Backup files are not needed, because we have git ;-) 107 | _UpgradeReport_Files/ 108 | Backup*/ 109 | UpgradeLog*.XML 110 | 111 | 112 | /src/Sample/CanalSharp.AspNetCore.Sample/obj 113 | /src/Sample/CanalSharp.AspNetCore.Sample/bin 114 | /src/Sample/CanalSharp.AspNetCore.Sample/.vs/CanalSharp.AspNetCore.Sample/DesignTimeBuild/.dtbcache 115 | /src/Sample/CanalSharp.AspNetCore.Sample/.vs/CanalSharp.AspNetCore.Sample/v15/.suo 116 | /src/Sample/CanalSharp.AspNetCore.Sample/.vs/CanalSharp.AspNetCore.Sample/v15/Server/sqlite3/db.lock 117 | /src/Sample/CanalSharp.AspNetCore.Sample/.vs/CanalSharp.AspNetCore.Sample/v15/Server/sqlite3/storage.ide 118 | /src/Sample/CanalSharp.AspNetCore.Sample/.vs/CanalSharp.AspNetCore.Sample/v15/Server/sqlite3/storage.ide-shm 119 | /src/Sample/CanalSharp.AspNetCore.Sample/.vs/CanalSharp.AspNetCore.Sample/v15/Server/sqlite3/storage.ide-wal 120 | /src/.vs/CanalSharp.AspNetCore/v15/Server/sqlite3/storage.ide-shm 121 | /src/.vs/CanalSharp.AspNetCore/v15/Server/sqlite3/*.ide-shm 122 | /src/.vs/CanalSharp.AspNetCore/v15/Server/sqlite3/*.ide-wal 123 | /src/.vs/CanalSharp.AspNetCore/v15/Server/sqlite3/*.ide 124 | /src/.vs/CanalSharp.AspNetCore/v15/Server/sqlite3/*.ide-shm 125 | /src/.vs/CanalSharp.AspNetCore/v15/Server/sqlite3/*.ide-wal 126 | /src/.vs/CanalSharp.AspNetCore/DesignTimeBuild/*.dtbcache 127 | -------------------------------------------------------------------------------- /src/Extensions/CanalAppBuilderExtensions.cs: -------------------------------------------------------------------------------- 1 | using CanalSharp.AspNetCore.CanalSharp; 2 | using CanalSharp.AspNetCore.Infrastructure; 3 | using CanalSharp.AspNetCore.Infrastructure.Enums; 4 | using Microsoft.AspNetCore.Builder; 5 | using Microsoft.AspNetCore.Hosting; 6 | using Microsoft.Extensions.Configuration; 7 | using Microsoft.Extensions.Logging; 8 | using System; 9 | 10 | namespace CanalSharp.AspNetCore.Extensions 11 | { 12 | public static class CanalAppBuilderExtensions 13 | { 14 | public static IApplicationBuilder UseCanalClient(this IApplicationBuilder app, IConfiguration configuration) 15 | { 16 | var isEnableCanalClient = Convert.ToBoolean(configuration["Canal:Enabled"] ?? "false"); 17 | if (isEnableCanalClient) 18 | { 19 | var outputOptions = BuildOutputOptions(configuration); 20 | var logger = app.ApplicationServices.GetService(typeof(ILogger)) as ILogger; 21 | var canalClient = BuildCanalClientHandler(configuration, outputOptions, logger); 22 | canalClient.Initialize(); 23 | canalClient.Start(); 24 | 25 | var appLifeTime = app.ApplicationServices.GetService(typeof(IApplicationLifetime)) as IApplicationLifetime; 26 | appLifeTime.ApplicationStopping.Register(() => 27 | { 28 | canalClient.Stop(); 29 | }); 30 | } 31 | 32 | return app; 33 | } 34 | 35 | /// 36 | /// 构造OutputOptions 37 | /// 38 | /// 配置文件 39 | /// OutputOptions 40 | private static OutputOptions BuildOutputOptions(IConfiguration configuration) 41 | { 42 | OutputOptions outputOptions = null; 43 | 44 | // MySql output 45 | if (configuration["Canal:Output:MySql:ConnStr"] != null) 46 | { 47 | outputOptions = new MySqlOutputOptions() 48 | { 49 | ConnectionString = configuration["Canal:Output:MySql:ConnStr"] ?? 50 | throw new ArgumentNullException("[CanalClient] MySql连接字符串不能为空!"), 51 | Output = OutputEnum.MySql 52 | }; 53 | } 54 | // Mongo output 55 | if (configuration["Canal:Output:Mongo:ConnStr"] != null) 56 | { 57 | outputOptions = new MongoOutputOptions() 58 | { 59 | ConnectionString = configuration["Canal:Output:Mongo:ConnStr"] ?? 60 | throw new ArgumentNullException("[CanalClient] Mongo连接字符串不能为空!"), 61 | DataBase = configuration["Canal:Output:Mongo:DataBase"] ?? 62 | throw new ArgumentNullException("[CanalClient] Mongo数据库名不能为空!"), 63 | Output = OutputEnum.Mongo 64 | }; 65 | } 66 | 67 | return outputOptions; 68 | } 69 | 70 | /// 71 | /// 构造CanalClientHandler 72 | /// 73 | private static CanalClientHandler BuildCanalClientHandler(IConfiguration configuration, OutputOptions outputOptions, ILogger canalLogger) 74 | { 75 | var canalClient = new CanalClientHandler( 76 | new CanalOption() 77 | { 78 | CanalServerIP = configuration["Canal:ServerIP"], 79 | CanalServerPort = Convert.ToInt32(configuration["Canal:ServerPort"]), 80 | Filter = configuration["Canal:Filter"] ?? string.Empty, 81 | Destination = configuration["Canal:Destination"] ?? string.Empty, 82 | UserName = configuration["Canal:UserName"] ?? string.Empty, 83 | Password = configuration["Canal:Password"] ?? string.Empty, 84 | SleepTime = Convert.ToInt32(configuration["Canal:SleepTime"] ?? "2000"), 85 | BufferSize = Convert.ToInt32(configuration["Canal:BufferSize"] ?? "1024"), 86 | LogSource = configuration["Canal:LogSource"] ?? "[Canal]" 87 | }, 88 | outputOptions, 89 | canalLogger); 90 | 91 | return canalClient; 92 | } 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # CanalSharp.AspNetCore 2 | 一个基于CanalSharp(一款针对.NET的Canal客户端开源项目)封装的ASP.NET Core业务组件,可以用于实时收集MySql数据更改记录并写入修改日志数据表中,可以选择MySql或者MongoDB作为输出记录。 3 | 4 | # 关于CanalSharp 5 | CanalSharp 是阿里巴巴开源项目 Canal 的 .NET 客户端。为 .NET 开发者提供一个更友好的使用 Canal 的方式。Canal 是mysql数据库binlog的增量订阅&消费组件,其作者是[WithLin](https://github.com/WithLin)和[晓晨](https://github.com/stulzq)。
6 | 更多关于CanalSharp的信息请浏览:https://github.com/CanalClient/CanalSharp
7 | 更多关于Canal的信息请浏览:https://github.com/alibaba/canal 8 | 9 | # 关于此组件 10 | CanalSharp.AspNetCore是一个基于CanalSharp的适用于ASP.NET Core的一个后台任务组件,它可以随着ASP.NET Core实例的启动而启动,目前采用轮询的方式对Canal Server进行监听,获得MySql行更改(RowChange)后写入MySql或MongoDB中指定的记录表中。 11 | 12 | # 准备工作 13 | 当前的canal开源版本支持8.0及以下的版本,针对阿里云RDS账号默认已经有binlog dump权限,不需要任何权限或者binlog设置,可以直接跳过这一步。 14 | 开启binlog写入功能,并且配置binlog模式为row。
15 | 修改C:\ProgramData\MySQL\MySQL Server 5.7\my.ini的以下内容 16 | ```sh 17 | log-bin=mysql-bin 18 | binlog-format=Row 19 | server-id=1 20 | ``` 21 | 22 | 23 | 重启数据库服务,测试修改是否生效 24 | ```sh 25 | show variables like 'binlog_format'; 26 | show variables like 'log_bin'; 27 | ``` 28 | 29 | 创建一个Canal用于获取binlog的用户并授予权限 30 | ```sh 31 | CREATE USER canal IDENTIFIED BY canal; 32 | GRANT SELECT, REPLICATION SLAVE, REPLICATION CLIENT ON *.* TO canal @'%'; 33 | FLUSH PRIVILEGES; 34 | ``` 35 | 36 | # 安装Canal-Server 37 | 通过Docker拉取Canal镜像: 38 | ```sh 39 | docker pull canal/canal-server:v1.1.2 40 | ``` 41 | 通过以下命令启动Canal实例: 42 | ```sh 43 | docker run --restart=always --name core_productservice_canal \ 44 | -e canal.instance.master.address=192.168.16.150:3306 \ 45 | -e canal.instance.dbUsername=canal \ 46 | -e canal.instance.dbPassword=canal \ 47 | -e canal.destinations=products \ 48 | -e canal.instance.defaultDatabaseName=products_dev \ 49 | -e canal.instance.filter.regex=products_dev\\..* \ 50 | -e canal.instance.filter.black.regex=products_dev\\.canal.* \ 51 | -p 8001:11111 \ 52 | -d canal/canal-server:v1.1.2 53 | ``` 54 | `PS`: 其中name、destinations、defaultDatabaseName、filter根据要监听的业务数据库按需修改。 55 | 56 | # 使用CanalSharp.AspNetCore 57 | 首先,通过NuGet或项目引用添加该组件,搜索CanalSharp.AspNetCore:[![CanalSharp.AspNetCore](https://img.shields.io/nuget/v/CanalSharp.AspNetCore.svg)](https://www.nuget.org/packages/CanalSharp.AspNetCore/) | [![CanalSharp.AspNetCore](https://img.shields.io/nuget/dt/CanalSharp.AspNetCore.svg)](https://www.nuget.org/packages/CanalSharp.AspNetCore/) 58 | [![N|Nuget](https://www.cnblogs.com/images/cnblogs_com/edisonchou/1260867/o_Nuget.png)](https://www.cnblogs.com/images/cnblogs_com/edisonchou/1260867/o_Nuget.png)
59 | 60 | 其次,在配置文件(appSettings.json)中添加以下配置项:MySql和MongoDB是二选一的配置,不可同时设置。 61 | ```sh 62 | "Canal": { 63 | "Enabled": true, 64 | "LogSource": "Core.Product.Canal", 65 | "ServerIP": "192.168.16.190", // Canal-Server所在的服务器IP 66 | "ServerPort": 8001, // Canal-Server所在的服务器Port 67 | "Destination": "products", // 建议与Canal-Server中配置的destination保持一致 68 | "Filter": "products_dev\\..*", // 建议与Canal-Server中配置的filter保持一致 69 | "SleepTime": 50, // SleepTime越短监听频率越高但也越耗CPU 70 | "BufferSize": 2048, // 每次监听获取的数据量大小,单位为字节 71 | "Output": { 72 | "MySql":{ 73 | "ConnStr": "Server=192.168.16.150;Port=3306;Database=products_dev;Uid=dev;Pwd=xdp" // 要输出的日志记录表所在的MySql连接字符串 74 | }, 75 | "Mongo":{ 76 | "ConnStr": "mongodb://192.168.16.150:27017", // 要输出的日志记录表所在的MongDB连接字符串 77 | "DataBase": "productrs_dev" // 要输出的日志记录表所在的MongDB数据库名 78 | }, 79 | } 80 | } 81 | ``` 82 | 最后,在StartUp类中的Configure方法中加入以下代码行: 83 | ```sh 84 | public void Configure(IApplicationBuilder app, IHostingEnvironment env) 85 | { 86 | ...... 87 | app.UseCanalClient(Configuration); 88 | } 89 | ``` 90 | 91 | # 示例项目 92 | >[CanalSharp.AspNetCore.Sample](https://github.com/EdisonChou/CanalSharp.AspNetCore/tree/master/sample) 93 | 94 | # 效果展示 95 | 当在指定要监听的数据库对某张表的某行数据进行Update或Delete操作后,又或者进行Insert行操作后。 96 | ## MySql 97 | 如果选择输出到MySql数据库,那么canal.logs表会自动记录变更的记录数据如下图: 98 | [![N|DEMO1](https://www.cnblogs.com/images/cnblogs_com/edisonchou/1260867/o_canal.logs.show.png)](https://www.cnblogs.com/images/cnblogs_com/edisonchou/1260867/o_canal.logs.show.png)
99 | `PS`: INSERT操作会记录新增的数据行数据到CurrentValue列,DELETE操作会记录删除的数据行数据到PreviousValue列,UPDATE操作则会记录修改前PreviousValue和修改后的值CurrentValue。 100 | ## MongoDB 101 | 如果选择输出到MongoDB,那么会自动记录变更数据如下图: 102 | [![N|DEMO2](https://www.cnblogs.com/images/cnblogs_com/edisonchou/1260867/o_MongoDB_Record.png)](https://www.cnblogs.com/images/cnblogs_com/edisonchou/1260867/o_MongoDB_Record.png) 103 | 104 | 105 | 106 | 107 | -------------------------------------------------------------------------------- /src/CanalSharp/CanalClientHandler.cs: -------------------------------------------------------------------------------- 1 | using CanalSharp.AspNetCore.Infrastructure; 2 | using CanalSharp.AspNetCore.Utils; 3 | using CanalSharp.Client; 4 | using CanalSharp.Client.Impl; 5 | using Com.Alibaba.Otter.Canal.Protocol; 6 | using Microsoft.Extensions.Logging; 7 | using System; 8 | using System.Collections.Generic; 9 | using System.Linq; 10 | using System.Text; 11 | using System.Threading; 12 | using System.Threading.Tasks; 13 | 14 | namespace CanalSharp.AspNetCore.CanalSharp 15 | { 16 | public class CanalClientHandler : ICanalClientHandler, IDisposable 17 | { 18 | private readonly CanalOption _xdpCanalOption; 19 | private readonly ILogger _canalLogger; 20 | private readonly CancellationTokenSource _cts; 21 | private readonly OutputOptions _options; 22 | 23 | private ICanalConnector _canalConnector; 24 | private ICanalRepository _canalRepository; 25 | private bool _disposed; 26 | private Task _compositeTask; 27 | 28 | public CanalClientHandler(CanalOption xdpCanalOption, OutputOptions options, ILogger canalLogger) 29 | { 30 | _xdpCanalOption = xdpCanalOption; 31 | _canalLogger = canalLogger; 32 | _options = options; 33 | _cts = new CancellationTokenSource(); 34 | } 35 | 36 | public void Initialize() 37 | { 38 | _canalLogger?.LogDebug("Starting to initialize log database."); 39 | 40 | _canalRepository = CanalRepositoryFactory.GetCanalRepositoryInstance(_options); 41 | _canalRepository.InitializeAsync(); 42 | 43 | _canalLogger?.LogDebug("Finished to initialize log database."); 44 | } 45 | 46 | public void Start() 47 | { 48 | _canalLogger?.LogDebug($"### [{_xdpCanalOption.LogSource}] Canal Client starting..."); 49 | 50 | Task.Factory.StartNew( 51 | () => 52 | { 53 | // 创建一个简单CanalClient连接对象(此对象不支持集群) 54 | // 传入参数分别为 Canal-Server地址、端口、Destination、用户名、密码 55 | _canalConnector = CanalConnectors.NewSingleConnector( 56 | _xdpCanalOption.CanalServerIP, 57 | _xdpCanalOption.CanalServerPort, 58 | _xdpCanalOption.Destination, 59 | _xdpCanalOption.UserName, 60 | _xdpCanalOption.Password); 61 | 62 | // 连接 Canal 63 | _canalConnector.Connect(); 64 | 65 | // 订阅,同时传入Filter,如果不传则以Canal的Filter为准。 66 | // Filter是一种过滤规则,通过该规则的表数据变更才会传递过来 67 | _canalConnector.Subscribe(_xdpCanalOption.Filter); 68 | 69 | while (true) 70 | { 71 | // 获取数据 BufferSize表示数据大小,单位为字节,默认会发送ACK来表示消费成功 72 | var message = _canalConnector.Get(_xdpCanalOption.BufferSize); 73 | // 也可以使用下面这个GetWithoutAck方法表示不发送ACK来表示消费成功 74 | //var message = _canalConnector.GetWithoutAck(_xdpCanalOption.BufferSize); 75 | 76 | // 批次id 可用于回滚 77 | var batchId = message.Id; 78 | 79 | if (batchId == -1 || message.Entries.Count <= 0) 80 | { 81 | Thread.Sleep(_xdpCanalOption.SleepTime); 82 | continue; 83 | } 84 | 85 | // 记录变更数据到自定义业务持久化存储区域 86 | if (message.Entries.Count > 0) 87 | { 88 | RecordChanges(message.Entries); 89 | } 90 | } 91 | }, 92 | _cts.Token, 93 | TaskCreationOptions.LongRunning, 94 | TaskScheduler.Default); 95 | 96 | _compositeTask = Task.CompletedTask; 97 | 98 | _canalLogger?.LogDebug($"### [{_xdpCanalOption.LogSource}] Canal Client started..."); 99 | } 100 | 101 | public void Stop() 102 | { 103 | _canalLogger?.LogDebug($"### [{_xdpCanalOption.LogSource}] Canal Client stopping..."); 104 | 105 | Dispose(); 106 | 107 | _canalLogger?.LogDebug($"### [{_xdpCanalOption.LogSource}] Canal Client stoped..."); 108 | } 109 | 110 | public void Dispose() 111 | { 112 | if (_disposed) 113 | { 114 | return; 115 | } 116 | 117 | _disposed = true; 118 | _cts.Cancel(); 119 | 120 | try 121 | { 122 | _compositeTask.Wait(TimeSpan.FromSeconds(2)); 123 | } 124 | catch (AggregateException ex) 125 | { 126 | var innerEx = ex.InnerExceptions[0]; 127 | if (!(innerEx is OperationCanceledException)) 128 | { 129 | _canalLogger?.LogError($"### [{_xdpCanalOption.LogSource}] {innerEx.Message}"); 130 | } 131 | } 132 | } 133 | 134 | #region 私有内部方法 135 | 136 | // 根据不同事件类型进行记录 137 | private void RecordChanges(List entrys) 138 | { 139 | // 一个entry表示一个数据库变更 140 | foreach (var entry in entrys) 141 | { 142 | if (entry.EntryType == EntryType.Transactionbegin || entry.EntryType == EntryType.Transactionend) 143 | { 144 | continue; 145 | } 146 | 147 | RowChange rowChange = null; 148 | 149 | try 150 | { 151 | // 获取行变更 152 | rowChange = RowChange.Parser.ParseFrom(entry.StoreValue); 153 | } 154 | catch (Exception ex) 155 | { 156 | _canalLogger?.LogError($"### [{_xdpCanalOption.LogSource}] {ex.Message}"); 157 | continue; 158 | } 159 | 160 | if (rowChange != null) 161 | { 162 | // 获取变更行的事件类型 163 | EventType eventType = rowChange.EventType; 164 | 165 | foreach (var rowData in rowChange.RowDatas) 166 | { 167 | if (eventType == EventType.Delete) 168 | { 169 | // 如果是Delete事件类型 170 | PostRecords(rowData.BeforeColumns.ToList(), entry, "Delete"); 171 | } 172 | else if (eventType == EventType.Insert) 173 | { 174 | // 如果是Insert事件类型 175 | PostRecords(rowData.AfterColumns.ToList(), entry, "Insert"); 176 | } 177 | else 178 | { 179 | // 如果是Update事件类型 180 | PostUpdatedRecords(rowData.BeforeColumns.ToList(), rowData.AfterColumns.ToList(), entry); 181 | } 182 | } 183 | } 184 | } 185 | } 186 | 187 | // 发送Insert或Delete事件类型的变更记录到指定服务的数据存储中 188 | private void PostRecords(List columns, Entry entry, string eventType) 189 | { 190 | _canalLogger?.LogDebug($"[{_xdpCanalOption.LogSource}]", $"### One {eventType} event on {entry.Header.SchemaName} recording."); 191 | 192 | StringBuilder recordBuilder = new StringBuilder(); 193 | recordBuilder.Append("{"); 194 | 195 | for (int i = 0; i < columns.Count; i++) 196 | { 197 | var column = columns[i]; 198 | if (i == columns.Count - 1) 199 | { 200 | recordBuilder.Append($"\"{column.Name}\":{column.Value ?? string.Empty}"); 201 | } 202 | else 203 | { 204 | recordBuilder.Append($"\"{column.Name}\":{column.Value ?? string.Empty},"); 205 | } 206 | } 207 | 208 | recordBuilder.Append("}"); 209 | 210 | List changeLogs = new List(); 211 | ChangeLog changeLog = new ChangeLog 212 | { 213 | SchemaName = entry.Header.SchemaName, 214 | TableName = entry.Header.TableName, 215 | EventType = entry.Header.EventType.ToString(), 216 | ExecuteTime = DateConvertUtil.ToDateTime(entry.Header.ExecuteTime) 217 | }; 218 | 219 | switch (entry.Header.EventType) 220 | { 221 | case EventType.Insert: 222 | changeLog.CurrentValue = recordBuilder.ToString(); 223 | break; 224 | case EventType.Delete: 225 | changeLog.PreviousValue = recordBuilder.ToString(); 226 | break; 227 | } 228 | 229 | changeLogs.Add(changeLog); 230 | _canalRepository = CanalRepositoryFactory.GetCanalRepositoryInstance(_options); 231 | _canalRepository.SaveChangeHistoriesAsync(changeLogs); 232 | 233 | _canalLogger?.LogDebug($"[{_xdpCanalOption.LogSource}]", $"### One {eventType} event on {entry.Header.SchemaName} recorded."); 234 | } 235 | 236 | // 发送Update事件类型的变更记录到指定的数据存储中 237 | private void PostUpdatedRecords(List beforeColumns, List afterColumns, Entry entry) 238 | { 239 | _canalLogger?.LogDebug($"[{_xdpCanalOption.LogSource}]", $"### One Update event on {entry.Header.SchemaName} recording."); 240 | 241 | List changeLogs = new List(); 242 | 243 | foreach (var before in beforeColumns) 244 | { 245 | foreach (var after in afterColumns) 246 | { 247 | if (after.Updated && before.Index == after.Index) 248 | { 249 | ChangeLog changeLog = new ChangeLog 250 | { 251 | SchemaName = entry.Header.SchemaName, 252 | TableName = entry.Header.TableName, 253 | EventType = entry.Header.EventType.ToString(), 254 | PreviousValue = before.Value, 255 | CurrentValue = after.Value, 256 | ExecuteTime = DateConvertUtil.ToDateTime(entry.Header.ExecuteTime), 257 | ColumnName = after.Name 258 | }; 259 | 260 | changeLogs.Add(changeLog); 261 | } 262 | } 263 | } 264 | 265 | _canalRepository = CanalRepositoryFactory.GetCanalRepositoryInstance(_options); 266 | _canalRepository.SaveChangeHistoriesAsync(changeLogs); 267 | 268 | _canalLogger?.LogDebug($"[{_xdpCanalOption.LogSource}]", $"### One Update event on {entry.Header.SchemaName} recorded."); 269 | } 270 | 271 | #endregion 272 | } 273 | } 274 | --------------------------------------------------------------------------------