Add project files.

This commit is contained in:
stulzq
2020-11-03 15:28:34 +08:00
parent b2f536ee94
commit b12d82dc02
40 changed files with 9229 additions and 0 deletions
+32
View File
@@ -0,0 +1,32 @@
---
name: ISSUE_TEMPLATE
about: ISSUE_TEMPLATE
title: ''
labels: ''
assignees: withlin
---
Please answer these questions before submitting your issue.
- Why do you submit this issue?
- [ ] Question or discussion
- [ ] Bug
- [ ] Requirement
- [ ] Feature or performance improvement
___
### Question
- What do you want to know?
___
### Bug
- Which version of Canal-Server, OS ,Mysql?
- What happen?
If possible, provide a way for reproducing the error. e.g. demo application.
___
### Requirement or improvement
- Please describe about your requirements or improvement suggestions.
+330
View File
@@ -0,0 +1,330 @@
## 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
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
# 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
# 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/
**/Properties/launchSettings.json
# StyleCop
StyleCopReport.xml
# Files built by Visual Studio
*_i.c
*_p.c
*_i.h
*.ilk
*.meta
*.obj
*.iobj
*.pch
*.pdb
*.ipdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*.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
# JustCode is a .NET coding add-in
.JustCode
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# AxoCover is a Code Coverage Tool
.axoCover/*
!.axoCover/settings.json
# 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
# 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
# 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
# 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/
# JetBrains Rider
.idea/
*.sln.iml
# CodeRush
.cr/
# 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/
+61
View File
@@ -0,0 +1,61 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.30413.136
MinimumVisualStudioVersion = 10.0.40219.1
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "01 Solution Items", "01 Solution Items", "{9F45639B-A9FA-4F6A-94EC-0D251FA3285D}"
ProjectSection(SolutionItems) = preProject
.gitignore = .gitignore
README.md = README.md
EndProjectSection
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "03 test", "03 test", "{BD70CDB7-94E9-4621-B702-DC04DB9D59EF}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "02 src", "02 src", "{4B78B79B-7EBE-405E-9BE3-3A59FFAD1910}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "04 sample", "04 sample", "{A4650FA0-4725-4956-90D3-F462F3C7474F}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CanalSharp.UnitTest", "test\CanalSharp.UnitTest\CanalSharp.UnitTest.csproj", "{1DFD44A5-2020-444F-B229-C5A6320A8DE0}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CanalSharp", "src\CanalSharp\CanalSharp.csproj", "{25BBA486-B374-4466-A565-507171898FBF}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "props", "props", "{D21B3144-16F2-4CED-8E3F-627C267A1635}"
ProjectSection(SolutionItems) = preProject
build\common.props = build\common.props
build\version.props = build\version.props
EndProjectSection
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CanalSharp.SimpleApp", "sample\CanalSharp.SimpleApp\CanalSharp.SimpleApp.csproj", "{BDFF31D3-BA2D-4B67-A805-E864A79A04AD}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{1DFD44A5-2020-444F-B229-C5A6320A8DE0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{1DFD44A5-2020-444F-B229-C5A6320A8DE0}.Debug|Any CPU.Build.0 = Debug|Any CPU
{1DFD44A5-2020-444F-B229-C5A6320A8DE0}.Release|Any CPU.ActiveCfg = Release|Any CPU
{1DFD44A5-2020-444F-B229-C5A6320A8DE0}.Release|Any CPU.Build.0 = Release|Any CPU
{25BBA486-B374-4466-A565-507171898FBF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{25BBA486-B374-4466-A565-507171898FBF}.Debug|Any CPU.Build.0 = Debug|Any CPU
{25BBA486-B374-4466-A565-507171898FBF}.Release|Any CPU.ActiveCfg = Release|Any CPU
{25BBA486-B374-4466-A565-507171898FBF}.Release|Any CPU.Build.0 = Release|Any CPU
{BDFF31D3-BA2D-4B67-A805-E864A79A04AD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{BDFF31D3-BA2D-4B67-A805-E864A79A04AD}.Debug|Any CPU.Build.0 = Debug|Any CPU
{BDFF31D3-BA2D-4B67-A805-E864A79A04AD}.Release|Any CPU.ActiveCfg = Release|Any CPU
{BDFF31D3-BA2D-4B67-A805-E864A79A04AD}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{1DFD44A5-2020-444F-B229-C5A6320A8DE0} = {BD70CDB7-94E9-4621-B702-DC04DB9D59EF}
{25BBA486-B374-4466-A565-507171898FBF} = {4B78B79B-7EBE-405E-9BE3-3A59FFAD1910}
{D21B3144-16F2-4CED-8E3F-627C267A1635} = {9F45639B-A9FA-4F6A-94EC-0D251FA3285D}
{BDFF31D3-BA2D-4B67-A805-E864A79A04AD} = {A4650FA0-4725-4956-90D3-F462F3C7474F}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {FD9B9146-8418-4F80-A666-9B47BE4F9C9C}
EndGlobalSection
EndGlobal
+201
View File
@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+66
View File
@@ -0,0 +1,66 @@
# CanalSharp
## 重构进度
目前重构的版本已经完全覆盖旧版本,且性能更高,代码更优美,实现了旧版本未实现的部分功能。
English README.md Will be provided after the refactoring is complete.
| Task | Status |
| ------------------- | ------ |
| protobuf 3 协议生成 | 已完成 |
| 对接 Canal | 已完成 |
| 数据订阅封装 | |
| 集群支持(热备) | |
| 数据发送到Kafka | |
| 数据发送到Redis | |
## 快速入门
>先决条件:安装Java环境和需要使用的数据库开启binlog
### 1.运行 Canal Server
(1)下载最新的 Canal Server https://github.com/alibaba/canal/releases/latest, 下载 `canal.deployer-版本号-SNAPSHOT.tar.gz` 文件
(2)配置
编辑文件 `conf/example/instance.properties`
设置 MySql 地址:`canal.instance.master.address=`
设置 MySql 用户:`canal.instance.dbUsername=`
设置 MySql 密码:`canal.instance.dbPassword=`
(3)运行
进入 `bin` 目录,根据你的系统选择脚本运行。
### 2.使用
````csharp
//初始化日志
using var loggerFactory = LoggerFactory.Create(builder =>
{
builder
.AddFilter("Microsoft", LogLevel.Debug)
.AddFilter("System", LogLevel.Information)
.AddConsole();
});
//创建连接
var conn=new SimpleCanalConnection(new SimpleCanalConnectionOptions(Canal Server 地址,端口 默认 11111,ClientId 自定义), loggerFactory.CreateLogger<SimpleCanalConnection>());
//连接到 Canal Server
await conn.ConnectAsync();
//订阅需要处理的数据
await conn.SubscribeAsync();
while (true)
{
//获取数据
var msg = await conn.GetAsync(1024);
await Task.Delay(300);
}
````
>更详细的文档将在重构完成后提供
Binary file not shown.

After

Width:  |  Height:  |  Size: 7.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 301 KiB

+33
View File
@@ -0,0 +1,33 @@
#!/usr/bin/env groovy Jenkinsfile
library 'JenkinsSharedLibraries'
pipeline {
agent {
node {
label 'slave-1'
}
}
environment {
NUGET_KEY = credentials('CanalSharp_Nuget_key')
}
triggers {
githubPush()
}
stages {
stage('Build') {
steps {
sh 'export DOTNET_SYSTEM_NET_HTTP_USESOCKETSHTTPHANDLER=0;dotnet build'
}
}
stage('Release') {
when {
branch "master"
expression { ciRelease action: 'check' }
}
steps {
withEnv(["nugetkey=${env.NUGET_KEY}"]) {
sh "chmod +x Release.sh; ./Release.sh"
}
}
}
}
}
+54
View File
@@ -0,0 +1,54 @@
#!/bin/sh
set -e
export DOTNET_SYSTEM_NET_HTTP_USESOCKETSHTTPHANDLER=0
# 编译项目
echo "begin build..."
dotnet build CanalSharp.sln -c Release
echo "build success"
# 创建nuget临时存放目录
publishdir=publish/nuget/$(date +%Y%m%d)
mkdir $publishdir -p
publishdir=$(cd ${publishdir}; pwd)
echo "begin pack..."
# 打包项目 IPTools 并输出到临时存放目录
echo "pack CanalSharp.Client..."
dotnet pack src/CanalSharp.Client/CanalSharp.Client.csproj -c Release -o ${publishdir}
echo "packCanalSharp.Client success"
echo "pack CanalSharp.Common..."
dotnet pack src/CanalSharp.Common/CanalSharp.Common.csproj -c Release -o ${publishdir}
echo "pack CanalSharp.Common success"
echo "pack CanalSharp.Protocol..."
dotnet pack src/CanalSharp.Protocol/CanalSharp.Protocol.csproj -c Release -o ${publishdir}
echo "pack CanalSharp.Protocol success"
#echo "pack CanalSharp.Logging.Microsoft.Extensions.Logging..."
#dotnet pack src/Logging/CanalSharp.Logging.Microsoft.Extensions.Logging/CanalSharp.Logging.Microsoft.Extensions.Logging.csproj -c Release -o ${publishdir}
#echo "pack CanalSharp.Logging.Microsoft.Extensions.Logging success"
#echo "pack CanalSharp.Logging.NLog..."
#dotnet pack src/Logging/CanalSharp.Logging.NLog/CanalSharp.Logging.NLog.csproj -c Release -o ${publishdir}
#echo "pack CanalSharp.Logging.NLog success"
# 发布到nuget.org
echo "begin push..."
for nugetfile in ${publishdir}/*; do
dotnet nuget push $nugetfile -k ${nugetkey} -s https://api.nuget.org/v3/index.json
done
echo "push success"
# 清理
if [[ $publishdir != "/" ]] ; then
rm -rf ${publishdir}
fi
+24
View File
@@ -0,0 +1,24 @@
<Project>
<Import Project="version.props" />
<PropertyGroup Label="Document">
<WarningsAsErrors>NU1605;NU1701</WarningsAsErrors>
<NoWarn>NU1701;1701;1702;1705;1591;CS1591</NoWarn>
</PropertyGroup>
<ItemGroup>
</ItemGroup>
<ItemGroup>
<None Remove="logs\**" />
<None Remove="*.DotSettings" />
</ItemGroup>
<Target Name="PrepublishScript" BeforeTargets="PrepareForPublish">
<ItemGroup>
<ProjectIncludeFile Include="*.json;*.pfx;Dockerfile" />
</ItemGroup>
<Copy SourceFiles="@(ProjectIncludeFile)" Condition="Exists(@(ProjectIncludeFile))" DestinationFolder="$(PublishDir)" SkipUnchangedFiles="false" />
</Target>
</Project>
+14
View File
@@ -0,0 +1,14 @@
<Project>
<PropertyGroup>
<FRAMEWORK_DEPENDENCY_VERSION>3.1.9</FRAMEWORK_DEPENDENCY_VERSION>
</PropertyGroup>
<PropertyGroup>
<VersionMajor>1</VersionMajor>
<VersionMinor>0</VersionMinor>
<VersionPatch>0</VersionPatch>
<VersionQuality></VersionQuality>
<VersionPrefix>$(VersionMajor).$(VersionMinor).$(VersionPatch)</VersionPrefix>
</PropertyGroup>
</Project>
+45
View File
@@ -0,0 +1,45 @@
# MEMBER CODE OF CONDUCT
The .NET Core Community (NCC) was created to doster an open, innovative, inclusive and welcoming community around open source .NET/.NET Core. To clarify expected behaviour in our communities we have adopted the [Contributor Covenant](contributor-covenant.org). This code of conduct has been adopted by [many other open source communities](contributor-covenant.org/adopters) and we feel it expresses our values well.
### Our Pledge
In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to make participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
### Our Standards
Examples of behavior that contributes to creating a positive environment include:
- Using welcoming and inclusive language
- Being respectful of differing viewpoints and experiences
- Gracefully accepting constructive criticism
- Focusing on what is best for the community
- Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
- The use of sexualized language or imagery and unwelcome sexual attention or advances
- Trolling, insulting/derogatory comments, and personal or political attacks
- Public or private harassment
- Publishing others’ private information, such as a physical or electronic address, without explicit permission
- Other conduct which could reasonably be considered inappropriate in a professional setting
### Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
### Scope
This Code of Conduct applies within all project spaces, and it also applies when an individual is representing the project or its community in public spaces. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.
### Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at [dotnet-community@outlook.com](dotnet-community@outlook.com). All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project’s leadership.
### Attribution
This Code of Conduct is adapted from the Contributor Covenant, version 1.4, available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
+51
View File
@@ -0,0 +1,51 @@
# 组织成员行为准则
.NET Core Community (NCC) 旨在建立一个围绕开源 .NET/.NET Core 的开放、创新、包容和热情的社区。为向大家表明我们社区的预期行动,我们编写了贡献者公约。许多其他开源社区已采用此行为准则,我们认为它很好地表达了我们的价值观。
### 我们的承诺
为建设开放友好的环境,我们贡献者和维护者承诺:不论年龄、体型、身体健全与否、民族、性征、性别认同与表征、经验水平、教育程度、社会地位、国籍、相貌、种族、信仰、性取向,我们项目和社区的参与者皆免于骚扰。
### 我们的准则
有助于创造积极环境的行为包括但不限于:
- 措辞友好且包容
- 尊重不同的观点和经验
- 耐心接受有益批评
- 关注对社区最有利的事情
- 与社区其他成员友善相处
参与者不应采取的行为包括但不限于:
- 发布与性有关的言论或图像、不受欢迎地献殷勤
- 捣乱/煽动/造谣行为、侮辱/贬损的评论、人身及政治攻击
- 公开或私下骚扰
- 未经明确授权便发布他人的资料,如住址、电子邮箱等
- 其他有理由认定为违反职业操守的不当行为
### 我们的义务
项目维护者有义务诠释何谓“妥当行为”,并妥善公正地纠正已发生的不当行为。
项目维护者有权利和义务去删除、编辑、拒绝违背本行为标准的评论(comments)、提交(commits)、代码、wiki 编辑、问题(issues)等贡献;项目维护者可暂时或永久地封禁任何他们认为行为不当、威胁、冒犯、有害的参与者。
### 适用范围
本行为标准适用于本项目。当有人代表本项目或本社区时,本标准亦适用于此人所处的公共平台。
代表本项目或本社区的情形包括但不限于:使用项目的官方电子邮件、通过官方媒体账号发布消息、作为指定代表参与在线或线下活动等。
代表本项目的行为可由项目维护者进一步定义及解释。
### 贯彻落实
可以致信 [dotnet-community@outlook.com](dotnet-community@outlook.com),向项目团队举报滥用、骚扰及不当行为。
维护团队将审议并调查全部投诉,妥善地予以必要的回应。项目团队有义务保密举报者信息。具体执行方针或将另行发布。
未切实遵守或执行本行为标准的项目维护人员,经项目负责人或其他成员决议,可能被暂时或永久地剥夺参与本项目的资格。
### 来源
本行为标准改编自参与者公约,版本 1.4 可在此查阅:https://www.contributor-covenant.org/zh-cn/version/1/4/code-of-conduct.html
@@ -0,0 +1,16 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\CanalSharp\CanalSharp.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="3.1.9" />
</ItemGroup>
</Project>
+92
View File
@@ -0,0 +1,92 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using CanalSharp.Connections;
using CanalSharp.Protocol;
using Microsoft.Extensions.Logging;
namespace CanalSharp.SimpleApp
{
class Program
{
private static ILogger _logger;
static async Task Main(string[] args)
{
using var loggerFactory = LoggerFactory.Create(builder =>
{
builder
.AddFilter("Microsoft", LogLevel.Debug)
.AddFilter("System", LogLevel.Information)
.AddConsole();
});
_logger = loggerFactory.CreateLogger<Program>();
var conn=new SimpleCanalConnection(new SimpleCanalConnectionOptions("127.0.0.1",11111,"12349"), loggerFactory.CreateLogger<SimpleCanalConnection>());
await conn.ConnectAsync();
await conn.SubscribeAsync();
while (true)
{
var msg = await conn.GetAsync(1024);
PrintEntry(msg.Entries);
await Task.Delay(300);
}
}
private static void PrintEntry(List<Entry> entries)
{
foreach (var entry in entries)
{
if (entry.EntryType == EntryType.Transactionbegin || entry.EntryType == EntryType.Transactionend)
{
continue;
}
RowChange rowChange = null;
try
{
rowChange = RowChange.Parser.ParseFrom(entry.StoreValue);
}
catch (Exception e)
{
_logger.LogError(e.ToString());
}
if (rowChange != null)
{
EventType eventType = rowChange.EventType;
_logger.LogInformation(
$"================> binlog[{entry.Header.LogfileName}:{entry.Header.LogfileOffset}] , name[{entry.Header.SchemaName},{entry.Header.TableName}] , eventType :{eventType}");
foreach (var rowData in rowChange.RowDatas)
{
if (eventType == EventType.Delete)
{
PrintColumn(rowData.BeforeColumns.ToList());
}
else if (eventType == EventType.Insert)
{
PrintColumn(rowData.AfterColumns.ToList());
}
else
{
_logger.LogInformation("-------> before");
PrintColumn(rowData.BeforeColumns.ToList());
_logger.LogInformation("-------> after");
PrintColumn(rowData.AfterColumns.ToList());
}
}
}
}
}
private static void PrintColumn(List<Column> columns)
{
foreach (var column in columns)
{
Console.WriteLine($"{column.Name} : {column.Value} update= {column.Updated}");
}
}
}
}
+32
View File
@@ -0,0 +1,32 @@
<Project Sdk="Microsoft.NET.Sdk">
<Import Project="../../build/common.props" />
<PropertyGroup>
<TargetFramework>netstandard2.1</TargetFramework>
</PropertyGroup>
<PropertyGroup Label="Document">
<DocumentationFile>bin\$(Configuration)\$(TargetFramework)\$(AssemblyName).xml</DocumentationFile>
</PropertyGroup>
<PropertyGroup Label="Package">
<Product>CanalSharp</Product>
<Authors>stulzq,withlin</Authors>
<Owners>stulzq,withlin</Owners>
<RepositoryUrl>https://github.com/dotnetcore/CanalSharp.git</RepositoryUrl>
<RepositoryType>git</RepositoryType>
<PackageProjectUrl>https://github.com/dotnetcore/CanalSharp</PackageProjectUrl>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="BeetleX" Version="1.5.4" />
<PackageReference Include="Google.Protobuf" Version="3.13.0" />
<PackageReference Include="JetBrains.Annotations" Version="2020.1.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="$(FRAMEWORK_DEPENDENCY_VERSION)" />
</ItemGroup>
<ItemGroup>
<Folder Include="Connections\HA\" />
</ItemGroup>
</Project>
@@ -0,0 +1,5 @@
<wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<s:Boolean x:Key="/Default/CodeInspection/NamespaceProvider/NamespaceFoldersToSkip/=connections_005Cha/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/CodeInspection/NamespaceProvider/NamespaceFoldersToSkip/=connections_005Csimple/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/CodeInspection/NamespaceProvider/NamespaceFoldersToSkip/=exceptions/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/CodeInspection/NamespaceProvider/NamespaceFoldersToSkip/=extensions/@EntryIndexedValue">True</s:Boolean></wpf:ResourceDictionary>
+128
View File
@@ -0,0 +1,128 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using JetBrains.Annotations;
namespace CanalSharp
{
[DebuggerStepThrough]
public static class Check
{
[ContractAnnotation("value:null => halt")]
public static T NotNull<T>(
T value,
[InvokerParameterName][NotNull] string parameterName)
{
if (value == null) throw new ArgumentNullException(parameterName);
return value;
}
[ContractAnnotation("value:null => halt")]
public static T NotNull<T>(
T value,
[InvokerParameterName][NotNull] string parameterName,
string message)
{
if (value == null) throw new ArgumentNullException(parameterName, message);
return value;
}
[ContractAnnotation("value:null => halt")]
public static string NotNull(
string value,
[InvokerParameterName][NotNull] string parameterName,
int maxLength = int.MaxValue,
int minLength = 0)
{
if (value == null) throw new ArgumentException($"{parameterName} can not be null!", parameterName);
if (value.Length > maxLength)
throw new ArgumentException($"{parameterName} length must be equal to or lower than {maxLength}!",
parameterName);
if (minLength > 0 && value.Length < minLength)
throw new ArgumentException($"{parameterName} length must be equal to or bigger than {minLength}!",
parameterName);
return value;
}
[ContractAnnotation("value:null => halt")]
public static string NotNullOrWhiteSpace(
string value,
[InvokerParameterName][NotNull] string parameterName,
int maxLength = int.MaxValue,
int minLength = 0)
{
if (string.IsNullOrWhiteSpace(value))
throw new ArgumentException($"{parameterName} can not be null, empty or white space!", parameterName);
if (value.Length > maxLength)
throw new ArgumentException($"{parameterName} length must be equal to or lower than {maxLength}!",
parameterName);
if (minLength > 0 && value.Length < minLength)
throw new ArgumentException($"{parameterName} length must be equal to or bigger than {minLength}!",
parameterName);
return value;
}
[ContractAnnotation("value:null => halt")]
public static string NotNullOrEmpty(
string value,
[InvokerParameterName][NotNull] string parameterName,
int maxLength = int.MaxValue,
int minLength = 0)
{
if (string.IsNullOrEmpty(value))
throw new ArgumentException($"{parameterName} can not be null or empty!", parameterName);
if (value.Length > maxLength)
throw new ArgumentException($"{parameterName} length must be equal to or lower than {maxLength}!",
parameterName);
if (minLength > 0 && value.Length < minLength)
throw new ArgumentException($"{parameterName} length must be equal to or bigger than {minLength}!",
parameterName);
return value;
}
[ContractAnnotation("value:null => halt")]
public static ICollection<T> NotNullOrEmpty<T>(ICollection<T> value,
[InvokerParameterName][NotNull] string parameterName)
{
if (value == null || !value.Any())
throw new ArgumentException(parameterName + " can not be null or empty!", parameterName);
return value;
}
public static string Length(
[CanBeNull] string value,
[InvokerParameterName][NotNull] string parameterName,
int maxLength,
int minLength = 0)
{
if (minLength > 0)
{
if (string.IsNullOrEmpty(value))
throw new ArgumentException(parameterName + " can not be null or empty!", parameterName);
if (value.Length < minLength)
throw new ArgumentException($"{parameterName} length must be equal to or bigger than {minLength}!",
parameterName);
}
if (value != null && value.Length > maxLength)
throw new ArgumentException($"{parameterName} length must be equal to or lower than {maxLength}!",
parameterName);
return value;
}
}
}
@@ -0,0 +1,13 @@
namespace CanalSharp.Connections.Enums
{
public enum FetchDataTimeoutUnitType
{
Nanosecond=0,
Millisecond=1,
Microsecond=2,
Second=3,
Minute=4,
Hour=5,
Day=6
}
}
@@ -0,0 +1,17 @@
using System;
namespace CanalSharp.Connections
{
/// <summary>
/// Connection state with Canal Server
/// </summary>
[Flags]
public enum ConnectionState
{
Closed = 2 << 0,
Connected = 2 << 1,
Subscribed = 2 << 2,
Unsubscribed = 2 << 3,
Unsubscribing = 2 << 4
}
}
@@ -0,0 +1,77 @@
using System;
using System.Threading.Tasks;
using CanalSharp.Connections.Enums;
using CanalSharp.Protocol;
namespace CanalSharp.Connections
{
/// <summary>
/// Canal Connection basic interface
/// </summary>
public interface ICanalConnection : IDisposable
{
/// <summary>
/// Connect to canal server.
/// </summary>
/// <returns></returns>
Task ConnectAsync();
/// <summary>
/// Subscribe to the data that needs to be received. Support repeat subscription to refresh filter setting.
/// </summary>
/// <param name="filter">Subscribe filter(Optional, default value is '.*\\..*')</param>
/// <returns></returns>
Task SubscribeAsync(string filter = ".*\\..*");
/// <summary>
/// UnSubscribe. If you need to unsubscribe, you should stop receiving data first.
/// </summary>
/// <param name="filter">UnSubscribe filter(Optional, default value is '.*\\..*')</param>
/// <returns></returns>
Task UnSubscribeAsync(string filter = ".*\\..*");
void DisConnect();
/// <summary>
/// Ack has received data.
/// </summary>
/// <param name="batchId"></param>
/// <returns></returns>
Task AckAsync(long batchId);
Task RollbackAsync(long batchId);
/// <summary>
/// Fetch data from Canal Server, have auto Ack and no timeout
/// </summary>
/// <param name="fetchSize">Fetch data Size. If you set the value to null or less than or equal to 0, the value will be reset to 1000. </param>
/// <returns></returns>
Task<Message> GetAsync(int fetchSize);
/// <summary>
/// Fetch data from Canal Server, have auto Ack
/// </summary>
/// <param name="fetchSize">Fetch data Size. If you set the value to null or less than or equal to 0, the value will be reset to 1000. </param>
/// <param name="timeout">Fetch data timeout. If you set the value to null or less than or equal to 0, the value will be reset to -1. -1 means no timeout.</param>
/// <param name="timeOutUnit">Timeout unit. Default value is <see cref="FetchDataTimeoutUnitType.Millisecond"/>.</param>
/// <returns></returns>
Task<Message> GetAsync(int fetchSize, long? timeout,
FetchDataTimeoutUnitType timeOutUnit = FetchDataTimeoutUnitType.Millisecond);
/// <summary>
/// Fetch data from Canal Server, but have no auto Ack and no timeout
/// </summary>
/// <param name="fetchSize">Fetch data Size. If you set the value to null or less than or equal to 0, the value will be reset to 1000. </param>
/// <returns></returns>
Task<Message> GetWithoutAckAsync(int fetchSize);
/// <summary>
/// Fetch data from Canal Server, but have no auto Ack
/// </summary>
/// <param name="fetchSize">Fetch data Size. If you set the value to null or less than or equal to 0, the value will be reset to 1000. </param>
/// <param name="timeout">Fetch data timeout. If you set the value to null or less than or equal to 0, the value will be reset to -1. -1 means no timeout.</param>
/// <param name="timeOutUnit">Timeout unit. Default value is <see cref="FetchDataTimeoutUnitType.Millisecond"/>.</param>
/// <returns></returns>
Task<Message> GetWithoutAckAsync(int fetchSize, long? timeout, FetchDataTimeoutUnitType timeOutUnit = FetchDataTimeoutUnitType.Millisecond);
}
}
@@ -0,0 +1,365 @@
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BeetleX;
using BeetleX.Clients;
using CanalSharp.Connections.Enums;
using CanalSharp.Protocol;
using CanalSharp.Utils;
using Google.Protobuf;
using Microsoft.Extensions.Logging;
namespace CanalSharp.Connections
{
/// <summary>
/// Simple connection, suitable for business scenarios with small data traffic. High Availability is not supported.
/// </summary>
public class SimpleCanalConnection : ICanalConnection
{
private readonly SimpleCanalConnectionOptions _options;
private readonly ILogger<SimpleCanalConnection> _logger;
private TcpClient _client;
public ConnectionState State { get; private set; }
public SimpleCanalConnection([NotNull] SimpleCanalConnectionOptions options, ILogger<SimpleCanalConnection> logger)
{
Check.NotNull(options, nameof(options));
_options = options;
_logger = logger;
State = ConnectionState.Closed;
}
/// <summary>
/// Connect to canal server.
/// </summary>
/// <returns></returns>
public async Task ConnectAsync()
{
ValidateState(ConnectionState.Closed, nameof(ConnectAsync));
_client = SocketFactory.CreateClient<TcpClient>(_options.Host, _options.Port);
var p = await _client.ReadPacketAsync();
// _client.Socket.ReceiveTimeout = _options.SoTimeout;
//Handshake
ValidatePackageType(p, PacketType.Handshake, 1);
var handshake = Handshake.Parser.ParseFrom(p.Body);
var seed = handshake.Seeds;
var newPassword = _options.Password;
if (_options.Password != null)
{
// encode password
newPassword = SecurityUtil.ByteArrayToHexString(SecurityUtil.Scramble411(Encoding.UTF8.GetBytes(_options.Password), seed.ToByteArray()));
}
//Auth
var data = new ClientAuth()
{
Username = _options.UserName,
Password = ByteString.CopyFromUtf8(newPassword ?? ""),
NetReadTimeout = _options.IdleTimeout,
NetWriteTimeout = _options.IdleTimeout
};
var packet = new Packet()
{
Type = PacketType.Clientauthentication,
Body = data.ToByteString()
}.ToByteArray();
//Send auth data
await _client.WritePacketAsync(packet);
p = await _client.ReadPacketAsync();
//Validate auth ack packet
p.ValidateAck();
//Set state
SetConnectionState(ConnectionState.Connected);
_logger.LogInformation($"Connect to canal server [{_options.Host}:{_options.Port}] success.");
}
/// <summary>
/// Subscribe to the data that needs to be received. Support repeat subscription to refresh filter setting.
/// </summary>
/// <param name="filter">Subscribe filter(Optional, default value is '.*\\..*')</param>
/// <returns></returns>
public async Task SubscribeAsync(string filter = ".*\\..*")
{
ValidateState(ConnectionState.Connected | ConnectionState.Subscribed | ConnectionState.Unsubscribed, nameof(SubscribeAsync));
//Sub data
var data = new Sub()
{
Destination = _options.Destination,
ClientId = _options.ClientId,
Filter = filter
};
//Assemble data package
var pack = new Packet()
{
Type = PacketType.Subscription,
Body = data.ToByteString()
}.ToByteArray();
//Send packet
await _client.WritePacketAsync(pack);
//Receive response
var p = await _client.ReadPacketAsync();
//Validate ack packet
p.ValidateAck();
//Set state
SetConnectionState(ConnectionState.Subscribed);
_logger.LogInformation($"Subscribe {filter} success.");
}
/// <summary>
/// UnSubscribe. If you need to unsubscribe, you should stop receiving data first.
/// </summary>
/// <param name="filter">UnSubscribe filter(Optional, default value is '.*\\..*')</param>
/// <returns></returns>
public async Task UnSubscribeAsync(string filter = ".*\\..*")
{
ValidateState(ConnectionState.Subscribed, nameof(UnSubscribeAsync));
//Unsub data
var data = new Unsub()
{
Destination = _options.Destination,
ClientId = _options.ClientId,
Filter = filter
};
var pack = new Packet()
{
Type = PacketType.Subscription,
Body = data.ToByteString()
}.ToByteArray();
await _client.WritePacketAsync(pack);
var p = await _client.ReadPacketAsync();
p.ValidateAck();
SetConnectionState(ConnectionState.Unsubscribed);
_logger.LogInformation($"UnSubscribe {filter} success.");
}
/// <summary>
/// Fetch data from Canal Server, have auto Ack and no timeout
/// </summary>
/// <param name="fetchSize">Fetch data Size. If you set the value to null or less than or equal to 0, the value will be reset to 1000. </param>
/// <returns></returns>
public Task<Message> GetAsync(int fetchSize)
{
return GetAsync(fetchSize, null);
}
/// <summary>
/// Fetch data from Canal Server, have auto Ack
/// </summary>
/// <param name="fetchSize">Fetch data Size. If you set the value to null or less than or equal to 0, the value will be reset to 1000. </param>
/// <param name="timeout">Fetch data timeout. If you set the value to null or less than or equal to 0, the value will be reset to -1. -1 means no timeout.</param>
/// <param name="timeOutUnit">Timeout unit. Default value is <see cref="FetchDataTimeoutUnitType.Millisecond"/>.</param>
/// <returns></returns>
public async Task<Message> GetAsync(int fetchSize, long? timeout,
FetchDataTimeoutUnitType timeOutUnit = FetchDataTimeoutUnitType.Millisecond)
{
var message = await GetWithoutAckAsync(fetchSize, timeout, timeOutUnit);
await AckAsync(message.Id);
return message;
}
/// <summary>
/// Fetch data from Canal Server, but have no auto Ack and no timeout
/// </summary>
/// <param name="fetchSize">Fetch data Size. If you set the value to null or less than or equal to 0, the value will be reset to 1000. </param>
/// <returns></returns>
public async Task<Message> GetWithoutAckAsync(int fetchSize)
{
return await GetWithoutAckAsync(fetchSize, null);
}
/// <summary>
/// Fetch data from Canal Server, but have no auto Ack
/// </summary>
/// <param name="fetchSize">Fetch data Size. If you set the value to null or less than or equal to 0, the value will be reset to 1000. </param>
/// <param name="timeout">Fetch data timeout. If you set the value to null or less than or equal to 0, the value will be reset to -1. -1 means no timeout.</param>
/// <param name="timeOutUnit">Timeout unit. Default value is <see cref="FetchDataTimeoutUnitType.Millisecond"/>.</param>
/// <returns></returns>
public async Task<Message> GetWithoutAckAsync(int fetchSize, long? timeout, FetchDataTimeoutUnitType timeOutUnit = FetchDataTimeoutUnitType.Millisecond)
{
ValidateState(ConnectionState.Subscribed, nameof(GetWithoutAckAsync));
var size = fetchSize <= 0 ? 1000 : fetchSize;
var time = (timeout == null || timeout < 0) ? -1 : timeout;
var get = new Get()
{
AutoAck = false,
Destination = _options.Destination,
ClientId = _options.ClientId,
FetchSize = size,
Timeout = (long)time,
Unit = (int)timeOutUnit
};
var pack = new Packet()
{
Type = PacketType.Get,
Body = get.ToByteString()
}.ToByteArray();
await _client.WritePacketAsync(pack);
var p = await _client.ReadPacketAsync();
return DeserializeMessage(p);
}
/// <summary>
/// Ack has received data.
/// </summary>
/// <param name="batchId"></param>
/// <returns></returns>
public async Task AckAsync(long batchId)
{
ValidateState(ConnectionState.Subscribed, nameof(AckAsync));
var ca = new ClientAck()
{
Destination = _options.Destination,
ClientId = _options.ClientId,
BatchId = batchId
};
var pack = new Packet()
{
Type = PacketType.Clientack,
Body = ca.ToByteString()
}.ToByteArray();
await _client.WritePacketAsync(pack);
_logger.LogDebug($"Ack {batchId} success.");
}
/// <summary>
/// Roll back consumption progress
/// </summary>
/// <param name="batchId"></param>
/// <returns></returns>
public async Task RollbackAsync(long batchId)
{
ValidateState(ConnectionState.Subscribed, nameof(RollbackAsync));
var ca = new ClientRollback()
{
Destination = _options.Destination,
ClientId = _options.ClientId,
BatchId = batchId
};
var pack = new Packet()
{
Type = PacketType.Clientrollback,
Body = ca.ToByteString()
}.ToByteArray();
await _client.WritePacketAsync(pack);
_logger.LogDebug($"Rollback {batchId} success.");
}
/// <summary>
/// Close connection
/// </summary>
public void DisConnect()
{
_client?.DisConnect();
SetConnectionState(ConnectionState.Closed);
}
/// <summary>
/// Disconnect TCP connection and dispose
/// </summary>
public void Dispose()
{
DisConnect();
_client?.Dispose();
}
private Message DeserializeMessage(Packet p)
{
// Check packet type
if (p.Type == PacketType.Ack)
{
var ackBody = Ack.Parser.ParseFrom(p.Body);
throw new CanalConnectionException("Received an error returned by the server: " +
ackBody.ErrorMessage);
}
if (p.Type != PacketType.Messages)
{
throw new CanalConnectionException($"Unexpected packet type received during fetch data: {p.Type}");
}
if (p.Compression != Compression.None && p.Compression != Compression.Compatibleproto2)
{
throw new CanalConnectionException($"Compression is not supported in this connection: {p.Compression}");
}
var messages = Messages.Parser.ParseFrom(p.Body);
Message result;
if (_options.LazyParseEntry)
{
result=new Message(messages.BatchId,true, messages.Messages_.ToList());
}
else
{
result=new Message(messages.BatchId);
foreach (var byteString in messages.Messages_)
{
result.AddEntry(Entry.Parser.ParseFrom(byteString));
}
}
return result;
}
private void ValidatePackageType(Packet p, PacketType expectPacketType, int expectPacketVersion)
{
if (p.Type != expectPacketType)
{
throw new CanalConnectionException($"Unexpected packet type received, expect: {expectPacketType}, actually: {p.Type}");
}
if (p.Version != 1)
{
throw new CanalConnectionException($"Unexpected packet version received, expect: {expectPacketVersion}, actually: {p.Version}");
}
}
private void ValidateState(ConnectionState expectState, string methodName)
{
if ((State & expectState) != State)
{
throw new CanalConnectionException($"Connection State is {State}, expect {expectState}, can not execute {methodName}.");
}
}
private void SetConnectionState(ConnectionState state)
{
State = state;
}
}
}
@@ -0,0 +1,57 @@
namespace CanalSharp.Connections
{
public class SimpleCanalConnectionOptions
{
public SimpleCanalConnectionOptions(string host, int port, string clientId)
{
Host = host;
Port = port;
ClientId = clientId;
}
/// <summary>
/// Canal Server Host(Require)
/// </summary>
public string Host { get; set; }
/// <summary>
/// Canal Server Port(Require)
/// </summary>
public int Port { get; set; }
/// <summary>
/// Canal Destination(Optional, default value is 'example')
/// </summary>
public string Destination { get; set; } = "example";
/// <summary>
/// Differentiate client instances(Require)
/// </summary>
public string ClientId { get; set; }
/// <summary>
/// Auth UserName(Optional, default value is empty string)
/// </summary>
public string UserName { get; set; } = "";
/// <summary>
/// Auth Password(Optional, default value is empty string)
/// </summary>
public string Password { get; set; } = "";
/// <summary>
/// The timeout of idle between client and server is 1 hour by default.(Optional, Unit: millisecond)
/// </summary>
public int IdleTimeout { get; set; } = 60 * 60 * 1000;
/// <summary>
/// Data read timeout.(Optional, default value is 60000, Unit: millisecond)
/// </summary>
public int SoTimeout { get; set; } = 60000;
/// <summary>
/// Automatically resolve the Entry object. If the maximum performance is considered, parsing can be delayed.(Optional, default value is false)
/// </summary>
public bool LazyParseEntry { get; set; } = false;
}
}
@@ -0,0 +1,20 @@
using System;
namespace CanalSharp
{
/// <summary>
/// Exception during connection
/// </summary>
public class CanalConnectionException:Exception
{
public CanalConnectionException(string message):base(message)
{
}
public CanalConnectionException(string message,Exception inner) : base(message,inner)
{
}
}
}
@@ -0,0 +1,72 @@
using System;
using System.IO;
using System.Threading.Tasks;
using BeetleX;
using BeetleX.Clients;
using CanalSharp.Protocol;
namespace CanalSharp
{
public static class ProtocolExtensions
{
/// <summary>
/// Validate Canal ack packet.
/// </summary>
/// <param name="p"></param>
public static void ValidateAck(this Packet p)
{
if (p.Type != PacketType.Ack)
{
throw new CanalConnectionException("Unexpected packet type when ack is expected.");
}
var ackBody = Ack.Parser.ParseFrom(p.Body);
if (ackBody.ErrorCode > 0)
{
throw new CanalConnectionException("Received an error returned by the server: " +
ackBody.ErrorMessage);
}
}
static readonly byte[] HeaderBuffer = new byte[4];
/// <summary>
/// Read Canal packet.
/// </summary>
/// <param name="client"></param>
/// <returns></returns>
public static async Task<Packet> ReadPacketAsync(this TcpClient client)
{
var reader = client.Receive();
await reader.ReadAsync(HeaderBuffer);
Array.Reverse(HeaderBuffer);
var bodyLength = BitConverter.ToInt32(HeaderBuffer);
while (reader.Length < bodyLength)
{
reader = client.Receive();
}
var bodyByte = reader.ReadBytes(bodyLength);
var p = Packet.Parser.ParseFrom(bodyByte.Data, bodyByte.Offset, bodyLength);
bodyByte.Dispose();
return p;
}
/// <summary>
/// Write Canal packet.
/// </summary>
/// <param name="client"></param>
/// <param name="data"></param>
/// <returns></returns>
public static async Task WritePacketAsync(this TcpClient client, byte[] data)
{
var headerBytes = BitConverter.GetBytes(data.Length);
Array.Reverse(headerBytes);
var writer = client.Stream.ToPipeStream();
await writer.WriteAsync(headerBytes);
await writer.WriteAsync(data);
await writer.FlushAsync();
}
}
}
@@ -0,0 +1,228 @@
syntax = "proto3";
option csharp_namespace = "CanalSharp.Protocol";
option optimize_for = SPEED;
/****************************************************************
* message model
*如果要在Enum中新增类型,确保以前的类型的下标值不变.
****************************************************************/
message Entry {
/**协议头部信息**/
Header header = 1;
///**打散后的事件类型**/ [default = ROWDATA]
oneof entryType_present{
EntryType entryType = 2;
}
/**传输的二进制数组**/
bytes storeValue = 3;
}
/**message Header**/
message Header {
/**协议的版本号**/ //[default = 1]
oneof version_present {
int32 version = 1;
}
/**binlog/redolog 文件名**/
string logfileName = 2;
/**binlog/redolog 文件的偏移位置**/
int64 logfileOffset = 3;
/**服务端serverId**/
int64 serverId = 4;
/** 变更数据的编码 **/
string serverenCode = 5;
/**变更数据的执行时间 **/
int64 executeTime = 6;
/** 变更数据的来源**/ //[default = MYSQL]
oneof sourceType_present {
Type sourceType = 7;
}
/** 变更数据的schemaname**/
string schemaName = 8;
/**变更数据的tablename**/
string tableName = 9;
/**每个event的长度**/
int64 eventLength = 10;
/**数据变更类型**/ // [default = UPDATE]
oneof eventType_present {
EventType eventType = 11;
}
/**预留扩展**/
repeated Pair props = 12;
/**当前事务的gitd**/
string gtid = 13;
}
/**每个字段的数据结构**/
message Column {
/**字段下标**/
int32 index = 1;
/**字段java中类型**/
int32 sqlType = 2;
/**字段名称(忽略大小写),在mysql中是没有的**/
string name = 3;
/**是否是主键**/
bool isKey = 4;
/**如果EventType=UPDATE,用于标识这个字段值是否有修改**/
bool updated = 5;
/** 标识是否为空 **/ //[default = false]
oneof isNull_present {
bool isNull = 6;
}
/**预留扩展**/
repeated Pair props = 7;
/** 字段值,timestamp,Datetime是一个时间格式的文本 **/
string value = 8;
/** 对应数据对象原始长度 **/
int32 length = 9;
/**字段mysql类型**/
string mysqlType = 10;
}
message RowData {
/** 字段信息,增量数据(修改前,删除前) **/
repeated Column beforeColumns = 1;
/** 字段信息,增量数据(修改后,新增后) **/
repeated Column afterColumns = 2;
/**预留扩展**/
repeated Pair props = 3;
}
/**message row 每行变更数据的数据结构**/
message RowChange {
/**tableId,由数据库产生**/
int64 tableId = 1;
/**数据变更类型**/ //[default = UPDATE]
oneof eventType_present {
EventType eventType = 2;
}
/** 标识是否是ddl语句 **/ // [default = false]
oneof isDdl_present {
bool isDdl = 10;
}
/** ddl/query的sql语句 **/
string sql = 11;
/** 一次数据库变更可能存在多行 **/
repeated RowData rowDatas = 12;
/**预留扩展**/
repeated Pair props = 13;
/** ddl/query的schemaName,会存在跨库ddl,需要保留执行ddl的当前schemaName **/
string ddlSchemaName = 14;
}
/**开始事务的一些信息**/
message TransactionBegin{
/**已废弃,请使用header里的executeTime**/
int64 executeTime = 1;
/**已废弃,Begin里不提供事务id**/
string transactionId = 2;
/**预留扩展**/
repeated Pair props = 3;
/**执行的thread Id**/
int64 threadId = 4;
}
/**结束事务的一些信息**/
message TransactionEnd{
/**已废弃,请使用header里的executeTime**/
int64 executeTime = 1;
/**事务号**/
string transactionId = 2;
/**预留扩展**/
repeated Pair props = 3;
}
/**预留扩展**/
message Pair{
string key = 1;
string value = 2;
}
/**打散后的事件类型,主要用于标识事务的开始,变更数据,结束**/
enum EntryType{
ENTRYTYPECOMPATIBLEPROTO2 = 0;
TRANSACTIONBEGIN = 1;
ROWDATA = 2;
TRANSACTIONEND = 3;
/** 心跳类型,内部使用,外部暂不可见,可忽略 **/
HEARTBEAT = 4;
GTIDLOG = 5;
}
/** 事件类型 **/
enum EventType {
EVENTTYPECOMPATIBLEPROTO2 = 0;
INSERT = 1;
UPDATE = 2;
DELETE = 3;
CREATE = 4;
ALTER = 5;
ERASE = 6;
QUERY = 7;
TRUNCATE = 8;
RENAME = 9;
/**CREATE INDEX**/
CINDEX = 10;
DINDEX = 11;
GTID = 12;
/** XA **/
XACOMMIT = 13;
XAROLLBACK = 14;
/** MASTER HEARTBEAT **/
MHEARTBEAT = 15;
}
/**数据库类型**/
enum Type {
TYPECOMPATIBLEPROTO2 = 0;
ORACLE = 1;
MYSQL = 2;
PGSQL = 3;
}
@@ -0,0 +1,153 @@
syntax = "proto3";
package com.alibaba.otter.canal.protocol;
option csharp_namespace = "CanalSharp.Protocol";
option optimize_for = SPEED;
enum Compression {
COMPRESSIONCOMPATIBLEPROTO2 = 0;
NONE = 1;
ZLIB = 2;
GZIP = 3;
LZF = 4;
}
enum PacketType {
//compatible
PACKAGETYPECOMPATIBLEPROTO2 = 0;
HANDSHAKE = 1;
CLIENTAUTHENTICATION = 2;
ACK = 3;
SUBSCRIPTION = 4;
UNSUBSCRIPTION = 5;
GET = 6;
MESSAGES = 7;
CLIENTACK = 8;
// management part
SHUTDOWN = 9;
// integration
DUMP = 10;
HEARTBEAT = 11;
CLIENTROLLBACK = 12;
}
message Packet {
//[default = 17];
oneof magic_number_present {
int32 magic_number = 1;
}
//[default = 1];
oneof version_present {
int32 version = 2;
};
PacketType type = 3;
//[default = NONE];
oneof compression_present {
Compression compression = 4;
}
bytes body = 5;
}
message HeartBeat {
int64 send_timestamp = 1;
int64 start_timestamp = 2;
}
message Handshake {
// [default = "utf8"];
oneof communication_encoding_present {
string communication_encoding = 1;
}
bytes seeds = 2;
Compression supported_compressions = 3;
}
// client authentication
message ClientAuth {
string username = 1;
bytes password = 2; // hashed password with seeds from Handshake message
// [default = 0]
oneof net_read_timeout_present {
int32 net_read_timeout = 3; // in seconds
}
// [default = 0];
oneof net_write_timeout_present {
int32 net_write_timeout = 4; // in seconds
}
string destination = 5;
string client_id = 6;
string filter = 7;
int64 start_timestamp = 8;
}
message Ack {
//[default = 0]
oneof error_code_present {
int32 error_code = 1;
}
string error_message = 2; // if something like compression is not supported, erorr_message will tell about it.
}
message ClientAck {
string destination = 1;
string client_id = 2;
int64 batch_id = 3;
}
// subscription
message Sub {
string destination = 1;
string client_id = 2;
string filter = 7;
}
// Unsubscription
message Unsub {
string destination = 1;
string client_id = 2;
string filter = 7;
}
// PullRequest
message Get {
string destination = 1;
string client_id = 2;
int32 fetch_size = 3;
//[default = -1]
oneof timeout_present {
int64 timeout = 4; // 默认-1时代表不控制
}
//[default = 2]
oneof unit_present {
int32 unit = 5;// 数字类型,0:纳秒,1:毫秒,2:微秒,3:秒,4:分钟,5:小时,6:天
}
//[default = false]
oneof auto_ack_present {
bool auto_ack = 6; // 是否自动ack
}
}
//
message Messages {
int64 batch_id = 1;
repeated bytes messages = 2;
}
// TBD when new packets are required
message Dump{
string journal = 1;
int64 position = 2;
// [default = 0]
oneof timestamp_present {
int64 timestamp = 3;
}
}
message ClientRollback{
string destination = 1;
string client_id = 2;
int64 batch_id = 3;
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+73
View File
@@ -0,0 +1,73 @@
using System;
using System.Collections;
using System.Collections.Generic;
using Google.Protobuf;
namespace CanalSharp.Protocol
{
[Serializable]
public class Message
{
public Message(long id)
{
Id = id;
Entries = new List<Entry>();
Raw = false;
RawEntries = new List<ByteString>();
}
public Message(long id, List<Entry> entries)
{
Id = id;
Entries = entries ?? new List<Entry>();
Raw = false;
RawEntries=new List<ByteString>();
}
public Message(long id,bool raw, IList entries)
{
Id = id;
Raw = raw;
if (raw)
{
RawEntries = entries switch
{
null => new List<ByteString>(),
List<ByteString> obj => obj,
_ => throw new ArgumentException($"Cannot convert to type {typeof(List<ByteString>)}", nameof(entries))
};
Entries=new List<Entry>();
}
else
{
Entries = entries switch
{
null => new List<Entry>(),
List<Entry> obj => obj,
_ => throw new ArgumentException($"Cannot convert to type {typeof(List<Entry>)}", nameof(entries))
};
RawEntries = new List<ByteString>();
}
}
public long Id { get; }
public List<Entry> Entries { get; }
public List<ByteString> RawEntries { get; }
public bool Raw { get; }
public void AddEntry(Entry entry)
{
Entries.Add(entry);
}
public void AddRasEntry(ByteString rawEntry)
{
RawEntries.Add(rawEntry);
}
}
}
+7
View File
@@ -0,0 +1,7 @@
# CanalSharp.Protocol
## 1.Get Start
Download protoc: https://github.com/protocolbuffers/protobuf/releases
Execute gen script.
+8
View File
@@ -0,0 +1,8 @@
@echo off
protoc --csharp_out=. Assets/CanalEntry.proto
protoc --csharp_out=. Assets/CanalPacket.proto
echo 完成
pause
+6
View File
@@ -0,0 +1,6 @@
#!/bin/sh
protoc --csharp_out=. Assets/CanalEntry.proto
protoc --csharp_out=. Assets/CanalPacket.proto
echo "完成"
+33
View File
@@ -0,0 +1,33 @@
using System;
using System.Security.Cryptography;
namespace CanalSharp.Utils
{
public class SecurityUtil
{
public static byte[] Scramble411(byte[] data, byte[] seed)
{
var sha1 = SHA1.Create();
var data1 = sha1.ComputeHash(data);
sha1.Initialize();
var data2 = sha1.ComputeHash(data1);
sha1.Initialize();
sha1.TransformBlock(seed, 0, seed.Length, null, 0);
var pass3 = sha1.ComputeHash(data2);
for (int i = 0; i < pass3.Length; i++)
{
pass3[i] = (byte)(pass3[i] ^ data1[i]);
}
return pass3;
}
public static string ByteArrayToHexString(byte[] data)
{
return BitConverter.ToString(data).Replace("-", "").ToLower();
}
}
}
@@ -0,0 +1,20 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.5.0" />
<PackageReference Include="xunit" Version="2.4.0" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.0" />
<PackageReference Include="coverlet.collector" Version="1.2.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\CanalSharp\CanalSharp.csproj" />
</ItemGroup>
</Project>
@@ -0,0 +1,105 @@
using System.Threading.Tasks;
using BeetleX;
using BeetleX.Clients;
using CanalSharp.Protocol;
using Google.Protobuf;
using Xunit;
namespace CanalSharp.UnitTest.Protocol
{
public class Protocol_Tests
{
private static TcpClient _client;
private static void InitClient()
{
_client= SocketFactory.CreateClient<TcpClient>(Settings.IpAddress, Settings.Port);
}
[Fact]
public async Task HandShake_ShouldBe_Success()
{
InitClient();
var p = await _client.ReadPacketAsync();
Assert.Equal(PacketType.Handshake,p.Type);
Assert.Equal(1,p.Version);
}
[Fact]
public async Task Auth_ShouldBe_Success()
{
InitClient();
await HandShake_ShouldBe_Success();
var data = new ClientAuth()
{
Username = Settings.UserName,
Password = ByteString.CopyFromUtf8(Settings.Password),
NetReadTimeout = 60 * 60 * 1000,
NetWriteTimeout = 60 * 60 * 1000
};
var packet = new Packet()
{
Type = PacketType.Clientauthentication,
Body = data.ToByteString()
}.ToByteArray();
await _client.WritePacketAsync(packet);
var p = await _client.ReadPacketAsync();
p.ValidateAck();
}
[Fact]
public async Task Subscribe_ShouldBe_Success()
{
InitClient();
await HandShake_ShouldBe_Success();
await Auth_ShouldBe_Success();
var data = new Sub()
{
Destination = Settings.Destination,
ClientId = Settings.ClientId,
Filter = string.IsNullOrEmpty(Settings.Filter) ? ".*\\..*" : Settings.Filter
};
var pack = new Packet()
{
Type = PacketType.Subscription,
Body = data.ToByteString()
}.ToByteArray();
await _client.WritePacketAsync(pack);
var p = await _client.ReadPacketAsync();
p.ValidateAck();
}
[Fact]
public async Task UnSubscribe_ShouldBe_Success()
{
InitClient();
await HandShake_ShouldBe_Success();
await Auth_ShouldBe_Success();
await Subscribe_ShouldBe_Success();
var data = new Unsub()
{
Destination = Settings.Destination,
ClientId = Settings.ClientId,
Filter = string.IsNullOrEmpty(Settings.Filter) ? ".*\\..*" : Settings.Filter
};
var pack = new Packet()
{
Type = PacketType.Subscription,
Body = data.ToByteString()
}.ToByteArray();
await _client.WritePacketAsync(pack);
var p = await _client.ReadPacketAsync();
p.ValidateAck();
}
}
}
+12
View File
@@ -0,0 +1,12 @@
# UnitTest Get Start
1.Restore database `db.sql`.
2.Configure database binlog settings.
3.Start a canal instance.
4.Configure the connection in `settings.cs`.
5.Run Tests
+13
View File
@@ -0,0 +1,13 @@
namespace CanalSharp.UnitTest
{
public class Settings
{
public const string IpAddress = "127.0.0.1";
public const int Port = 11111;
public const string UserName = "";
public const string Password = "";
public const string Destination = "example";
public const string ClientId = "12345";
public const string Filter = "canaltest\\..*";
}
}
+21
View File
@@ -0,0 +1,21 @@
CREATE DATABASE `canaltest` CHARACTER SET 'utf8mb4' COLLATE 'utf8mb4_general_ci';
use canaltest;
-- ----------------------------
-- Table structure for user_info
-- ----------------------------
DROP TABLE IF EXISTS `user_info`;
CREATE TABLE `user_info` (
`Id` int(11) NOT NULL AUTO_INCREMENT,
`Name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL,
`Age` int(11) NOT NULL,
PRIMARY KEY (`Id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 4 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of user_info
-- ----------------------------
INSERT INTO `user_info` VALUES (1, '张三', 25);
INSERT INTO `user_info` VALUES (2, '李四', 24);
INSERT INTO `user_info` VALUES (3, '王五', 23);