文章转载授权级别:B
无论是 Quartz.net 还是 MySql.Data 都是我们比较熟悉的库了,Quartz.net 如果配置为使用 MySql 数据库做持久化时,默认是硬编码了使用 MySql.Data 来操作 MySql 数据库的。下面是我的一些个人诉求和实践,和大家共同探讨一下。
0x01 为什么要替换 MySql.Data
MySql.Data 虽然是官方驱动,但实际上实现质量并不是很高。我和一些朋友都经历过在使用它做长时间的连接查询时异常崩溃,在 老农 菊巨 的推荐以后,我一直使用 MySqlConnector 这个 MySql 驱动。
因为我的项目都是使用了 MySqlConnector 这个驱动,此驱动为了兼容官方的写法,类名和命名空间基本保持一致,这就导致如果你同时引用这两个库后,再想创建 MySqlConnection 对象时,编译器无法识别到底是哪一个程序集的类型。
因此如果你项目中已经使用了 MySqlConnector,那么最好还是替换掉 Quarzt.net 默认使用的驱动。
0x02 测试 Quartz.net 使用 MySql.Data
在本地 MySql 数据库中创建测试数据库 quartz, 并通过执行脚本 https://raw.githubusercontent.com/dotnetcore/DotnetSpider/master/src/DotnetSpider.Portal/DDL/MySql.sql 来创建所需要的表
首先创建一个空的 Console 项目并添加 Quartz 这个包
修改 Program.cs 代码如下
class Program
{
public class HelloJob : IJob
{
public Task Execute(IJobExecutionContext context)
{
Console.WriteLine($"{DateTime.Now:yyyy-MM-dd HH:mm:ss} Greetings from HelloJob!");
return Task.CompletedTask;
}
}
static async Task Main(string[] args)
{
IScheduler scheduler = null;
try
{
var properties = new NameValueCollection
{
{"quartz.jobStore.type", "Quartz.Impl.AdoJobStore.JobStoreTX, Quartz"},
{"quartz.jobStore.dataSource", "myDs"},
{"quartz.serializer.type", "binary"},
{"quartz.dataSource.myDs.provider", "MySql"},
{
"quartz.dataSource.myDs.connectionString",
"Database='quartz';Data Source=localhost;password=1qazZAQ!;User ID=root;Port=3306;"
}
};
scheduler = await new StdSchedulerFactory(properties).GetScheduler();
await scheduler.Start();
if (!await scheduler.CheckExists(new JobKey("job1", "group1")))
{
var trigger = TriggerBuilder.Create().WithCronSchedule("*/5 * * * * ?").WithIdentity("trigger1")
.Build();
var job = JobBuilder.Create<HelloJob>().WithIdentity("job1", "group1")
.RequestRecovery(true).Build();
await scheduler.ScheduleJob(job, trigger);
}
Console.Read();
}
finally
{
if (scheduler != null)
{
await scheduler.Shutdown();
}
}
}
}
直接运行可以发现程序异常退出了,异常信息如下:
Unhandled Exception: Quartz.SchedulerException: Could not Initialize DataSource: myDs ---> System.ArgumentException: Error while reading metadata information for provider 'MySql'
Parameter name: providerName ---> Quartz.SchedulerConfigException: Could not parse property 'connectionType' into correct data type: Could not load file or assembly 'MySql.Data, Culture=neutral, PublicKeyToken=null'. The system cannot find the file specified.
---> System.IO.FileNotFoundException: Could not load file or assembly 'MySql.Data, Culture=neutral, PublicKeyToken=null'. The system cannot find the file specified.
可以得到明确的错误提示:未能找到 MySql.Data 程序集
引用 MySql.Data 包并重新运行程序,可以发现程序正常运行了,结果如下:
2019-09-26 22:20:46 Greetings from HelloJob!
2019-09-26 22:20:50 Greetings from HelloJob!
2019-09-26 22:20:55 Greetings from HelloJob!
0x03 测试添加 MySqlconnector
在上一小节中,我们成功的使用 MySql 数据库做为 Quartz 的持久化。在上面代码的基础之上,我们直接引用 MysqlConnector 包,看一下会有什么影响。运行后发现程序运行正常,那是不是意味着 MySql.Data 和 MysqlConnector 可以和平共处呢?如果我们想自己使用 MySqlConnection 时会发生什么呢?编译器报了如下错误:
Program.cs(23, 28): [CS0433] The type 'MySqlConnection' exists in both 'MySql.Data, Version=8.0.17.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d' and 'MySqlConnector, Version=0.59.0.0, Culture=neutral, PublicKeyToken=d33d3e53aa5f8c92'
这个结果很容易想到,因为两个程序集里有相同的命名空间,相同的类型,所以无法判断到底应该使用哪个类型。那为什么并不影响 Quartz.net 的正常运行呢?答案也是比较容易想到的:它用了反射,指定了程序集和类型。我们测试如下代码:
var ass = AppDomain.CurrentDomain.Load("MySqlConnector");
var type = ass.GetType("MySql.Data.MySqlClient.MySqlConnection");
var conn = (IDbConnection) Activator.CreateInstance(
type,
"Database='dotnetspider';Data Source=my.com;password=1qazZAQ!;User ID=root;Port=3306;");
有经验的同学肯定知道以上代码是能够正常运行的。
0x04 翻看 quartz.net 的源码并尝试替换
在查看了 Quartz.net 的源码之后发现,会发现针对 MySql 的配置有如下:
# MySQL
quartz.dbprovider.MySql.productName=MySQL, MySQL provider
quartz.dbprovider.MySql.assemblyName=MySql.Data
quartz.dbprovider.MySql.connectionType=MySql.Data.MySqlClient.MySqlConnection, MySql.Data
quartz.dbprovider.MySql.commandType=MySql.Data.MySqlClient.MySqlCommand, MySql.Data
quartz.dbprovider.MySql.parameterType=MySql.Data.MySqlClient.MySqlParameter, MySql.Data
quartz.dbprovider.MySql.parameterDbType=MySql.Data.MySqlClient.MySqlDbType, MySql.Data
quartz.dbprovider.MySql.parameterDbTypePropertyName=MySqlDbType
quartz.dbprovider.MySql.parameterNamePrefix=?
quartz.dbprovider.MySql.exceptionType=MySql.Data.MySqlClient.MySqlException, MySql.Data
quartz.dbprovider.MySql.useParameterNamePrefixInParameterCollection=true
quartz.dbprovider.MySql.bindByName=true
quartz.dbprovider.MySql.dbBinaryTypeName=Blob
果然,这里 hardcode 的程序为 MySql.Data,那么我们是否可以通过修改配置文件来替换数据库驱动呢?在第一章节的测试代码中,我们添加配置后的代码如下:
var properties = new NameValueCollection
{
{"quartz.dbprovider.MySql.assemblyName", "MySqlConnector"},
{"quartz.jobStore.type", "Quartz.Impl.AdoJobStore.JobStoreTX, Quartz"},
{"quartz.jobStore.dataSource", "myDs"},
{"quartz.serializer.type", "binary"},
{"quartz.dataSource.myDs.provider", "MySql"},
{
"quartz.dataSource.myDs.connectionString",
"Database='quartz';Data Source=localhost;password=1qazZAQ!;User ID=root;Port=3306;"
}
};
删除干扰因素:MySql.Data 包后运行程序,发现程序异常如下:
Unhandled Exception: Quartz.SchedulerException: Could not Initialize DataSource: myDs ---> System.ArgumentException: Error while reading metadata information for provider 'MySql'
Parameter name: providerName ---> Quartz.SchedulerConfigException: Could not parse property 'connectionType' into correct data type: Could not load file or assembly 'MySql.Data, Culture=neutral, PublicKeyToken=null'. The system cannot find the file specified.
---> System.IO.FileNotFoundException: Could not load file or assembly 'MySql.Data, Culture=neutral, PublicKeyToken=null'. The system cannot find the file specified.
at System.RuntimeTypeHandle.GetTypeByName(String name, Boolean throwOnError, Boolean ignoreCase, Boolean reflectionOnly, StackCrawlMarkHandle stackMark, IntPtr pPrivHostBinder, Boolean loadTypeFromPartialName, ObjectHandleOnStack type, ObjectHandleOnStack keepalive)
at System.RuntimeTypeHandle.GetTypeByName(String name, Boolean throwOnError, Boolean ignoreCase, Boolean reflectionOnly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean loadTypeFromPartialName)
at System.RuntimeTypeHandle.GetTypeByName(String name, Boolean throwOnError, Boolean ignoreCase, Boolean reflectionOnly, StackCrawlMark& stackMark, Boolean loadTypeFromPartialName)
at System.RuntimeType.GetType(String typeName, Boolean throwOnError, Boolean ignoreCase, Boolean reflectionOnly, StackCrawlMark& stackMark)
at System.Type.GetType(String typeName, Boolean throwOnError)
at Quartz.Util.ObjectUtils.ConvertValueIfNecessary(Type requiredType, Object newValue) in C:\projects\quartznet\src\Quartz\Util\ObjectUtils.cs:line 69
at Quartz.Util.ObjectUtils.SetPropertyValue(Object target, String propertyName, Object value) in C:\projects\quartznet\src\Quartz\Util\ObjectUtils.cs:line 200
at Quartz.Util.ObjectUtils.SetObjectProperties(Object obj, NameValueCollection props) in C:\projects\quartznet\src\Quartz\Util\ObjectUtils.cs:line 151
--- End of inner exception stack trace ---
at Quartz.Util.ObjectUtils.SetObjectProperties(Object obj, NameValueCollection props) in C:\projects\quartznet\src\Quartz\Util\ObjectUtils.cs:line 154
at Quartz.Impl.AdoJobStore.Common.EmbeddedAssemblyResourceDbMetadataFactory.GetDbMetadata(String providerName) in C:\projects\quartznet\src\Quartz\Impl\AdoJobStore\Common\EmbeddedAssemblyResourceDbMetadataFactory.cs:line 64
--- End of inner exception stack trace ---
at Quartz.Impl.AdoJobStore.Common.EmbeddedAssemblyResourceDbMetadataFactory.GetDbMetadata(String providerName) in C:\projects\quartznet\src\Quartz\Impl\AdoJobStore\Common\EmbeddedAssemblyResourceDbMetadataFactory.cs:line 70
at Quartz.Impl.AdoJobStore.Common.DbProvider.GetDbMetadata(String providerName) in C:\projects\quartznet\src\Quartz\Impl\AdoJobStore\Common\DbProvider.cs:line 112
at Quartz.Impl.AdoJobStore.Common.DbProvider..ctor(String dbProviderName, String connectionString) in C:\projects\quartznet\src\Quartz\Impl\AdoJobStore\Common\DbProvider.cs:line 74
at Quartz.Impl.StdSchedulerFactory.Instantiate() in C:\projects\quartznet\src\Quartz\Impl\StdSchedulerFactory.cs:line 607
--- End of inner exception stack trace ---
at Quartz.Impl.StdSchedulerFactory.Instantiate() in C:\projects\quartznet\src\Quartz\Impl\StdSchedulerFactory.cs:line 616
at Quartz.Impl.StdSchedulerFactory.GetScheduler(CancellationToken cancellationToken) in C:\projects\quartznet\src\Quartz\Impl\StdSchedulerFactory.cs:line 1114
at quartz.demo.Program.Main(String[] args) in /Users/lewis/Documents/codes/quartz.demo/quartz.demo/Program.cs:line 44
at quartz.demo.Program.Main(String[] args) in /Users/lewis/Documents/codes/quartz.demo/quartz.demo/Program.cs:line 67
at quartz.demo.Program.<Main>(String[] args)
可以猜测这个配置项目并没有起作用。通过堆栈信息,我们发现错误是在 DbProvider.cs:line 74,以此为突破口逐行代码扫过去,原来 DbProvider 静态加载了2个 DbMetadataFactory,一个是通过配置文件、另一个是通过内嵌的资源文件,而配置文件它却是通过 ConfigurationManager 这个类来获取的,也就是说我们代码里的配置并没有真正的生效。于是我们可以在项目中添加 App.config 文件并修改内容为如下:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="quartz" type="System.Configuration.NameValueSectionHandler, System.Configuration.ConfigurationManager, Version=4.0.1.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51" />
</configSections>
<quartz>
<add key="quartz.dbprovider.MySql.assemblyName" value="MySqlConnector" />
<add key="quartz.dbprovider.MySql.commandType" value="MySql.Data.MySqlClient.MySqlCommand, MySqlConnector"/>
<add key="quartz.dbprovider.MySql.parameterType" value="MySql.Data.MySqlClient.MySqlParameter, MySqlConnector"/>
<add key="quartz.dbprovider.MySql.parameterDbType" value="MySql.Data.MySqlClient.MySqlDbType, MySqlConnector"/>
<add key="quartz.dbprovider.MySql.parameterDbTypePropertyName" value="MySqlDbType"/>
<add key="quartz.dbprovider.MySql.connectionType" value="MySql.Data.MySqlClient.MySqlConnection, MySqlConnector"/>
<add key="quartz.dbprovider.MySql.parameterNamePrefix" value="?"/>
<add key="quartz.dbprovider.MySql.exceptionType" value="MySql.Data.MySqlClient.MySqlException, MySqlConnector"/>
</quartz>
</configuration>
重启程序可以发现正常运行了,回过头来看代码,我们能够发现,驱动相关的配置是从内嵌配置和 App.config 中读取的,而数据库实例的配置则可以通过参数传递到 Factory 中。那么是否可以完全通过配置文件来设置呢?修改配置文件如下:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="quartz" type="System.Configuration.NameValueSectionHandler, System.Configuration.ConfigurationManager, Version=4.0.1.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51" />
</configSections>
<quartz>
<add key="quartz.dbprovider.MySql.assemblyName" value="MySqlConnector" />
<add key="quartz.dbprovider.MySql.commandType" value="MySql.Data.MySqlClient.MySqlCommand, MySqlConnector"/>
<add key="quartz.dbprovider.MySql.parameterType" value="MySql.Data.MySqlClient.MySqlParameter, MySqlConnector"/>
<add key="quartz.dbprovider.MySql.parameterDbType" value="MySql.Data.MySqlClient.MySqlDbType, MySqlConnector"/>
<add key="quartz.dbprovider.MySql.parameterDbTypePropertyName" value="MySqlDbType"/>
<add key="quartz.dbprovider.MySql.connectionType" value="MySql.Data.MySqlClient.MySqlConnection, MySqlConnector"/>
<add key="quartz.dbprovider.MySql.parameterNamePrefix" value="?"/>
<add key="quartz.dbprovider.MySql.exceptionType" value="MySql.Data.MySqlClient.MySqlException, MySqlConnector"/>
<add key="quartz.jobStore.type" value="Quartz.Impl.AdoJobStore.JobStoreTX, Quartz"/>
<add key="quartz.jobStore.dataSource" value="myDs"/>
<add key="quartz.serializer.type" value="binary"/>
<add key="quartz.dataSource.myDs.provider" value="MySql"/>
<add key="quartz.dataSource.myDs.connectionString" value="Database='quartz';Data Source=localhost;password=1qazZAQ!;User ID=root;Port=3306;"/>
</quartz>
</configuration>
同时代码中修改一行:
scheduler = await new StdSchedulerFactory().GetScheduler();
重启程序后得到结论:程序正常运行。
0x05 初步小结
至此,基本上已经清楚了,因为我基本上已经不再使用 App.config,当我尝试使用 quarzt.net 从网上找到的资料大多是配置 *.properties 文件,于是为了找替代,我通过构造传入了必要参数进 factory 来构造 scheduler。但这个参数迷惑了我以为所有的配置都会从此生效,实际上是对数据库驱动相关的(DbMetadata) 是只能通过配置文件来配置。
0x06 其它方式
因为现在我们基本上都是使用 appsettings.json 来做配置了, App.config 实在是使用得少,可能有人就会对此有癖好不想添加一个新的配置文件来解决这个问题。那么接着往下分析代码,我们会发现,实际上作者提供了一个配置:
quartz.dataSource.myDs.connectionProvider.type
即我们是可以自己实际数据库相关的 Provider 的,于是我们回到第一小节的 NameCollection 中修改为只有一个配置:
{ "quartz.dataSource.myDs.connectionProvider.type", "quartz.demo.MySqlDbProvider, quartz.demo"}
同时添加如下 Provider 的实现:
public class MySqlDbProvider : IDbProvider
{
public string Provider { get; set; }
public MySqlDbProvider()
{
ConnectionString = "Database='quartz';Data Source=localhost;password=1qazZAQ!;User ID=root;Port=3306;";
var metadata = new MySqlMetadata();
Metadata = metadata;
}
public void Initialize()
{
}
public DbCommand CreateCommand()
{
return new MySqlCommand();
}
public DbConnection CreateConnection()
{
return new MySqlConnection(ConnectionString);
}
public void Shutdown()
{
}
public string ConnectionString { get; set; }
public DbMetadata Metadata { get; }
}
public class MySqlMetadata : DbMetadata
{
private readonly Enum _dbBinaryType;
public MySqlMetadata()
{
var dbBinaryTypeName = "Blob";
_dbBinaryType = (Enum) Enum.Parse(Type.GetType("MySql.Data.MySqlClient.MySqlDbType, MySqlConnector"),
dbBinaryTypeName);
DbBinaryTypeName = dbBinaryTypeName;
var parameterDbTypePropertyName = "MySqlDbType";
ParameterDbTypePropertyName = parameterDbTypePropertyName;
ConnectionType = Type.GetType("MySql.Data.MySqlClient.MySqlConnection, MySqlConnector");
CommandType = Type.GetType("MySql.Data.MySqlClient.MySqlCommand, MySqlConnector");
ParameterDbType = Type.GetType("MySql.Data.MySqlClient.MySqlDbType, MySqlConnector");
ParameterType = Type.GetType("MySql.Data.MySqlClient.MySqlParameter, MySqlConnector");
ParameterDbTypeProperty = ParameterType.GetProperty("MySqlDbType");
if (ParameterDbTypeProperty == null)
{
throw new ArgumentException($"Couldn't parse parameter db type for database type '{ProductName}'");
}
ExceptionType = Type.GetType("MySql.Data.MySqlClient.MySqlException, MySqlConnector");
}
public override string AssemblyName => "MySqlConnector";
public override string ProductName => "MySQL, MySQL provider";
public override string ParameterNamePrefix => "?";
public override bool BindByName => true;
public override Enum DbBinaryType => _dbBinaryType;
}
直接运行验证是不是正常。以上 Provider 实现是 hardcode 各项值,实际可以通过从 appsettings.json 中读取来设置。这样就达到:
统一使用一个驱动库
不添加额外配置文件
0x07 总结
开源的好处就是我们可以直接查阅代码去学习,并找出其中的关键点然后自己可以做各种各样的 workaround。.NET 在国内的情况是真的岌岌可危了,希望 .neter 能够多花时间在开源生态的建设上,少打嘴炮,多研究代码,多写代码。