You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

mysql.md 2.1 KiB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. # MySQL
  2. MySQL 是一个开源的关系型数据库,你可以使用 MySQL 来作为 CAP 消息的持久化。
  3. ## 配置
  4. 要使用 MySQL 存储,你需要从 NuGet 安装以下扩展包:
  5. ```shell
  6. Install-Package DotNetCore.CAP.MySql
  7. ```
  8. 然后,你可以在 `Startup.cs` 的 `ConfigureServices` 方法中添加基于内存的配置项。
  9. ```csharp
  10. public void ConfigureServices(IServiceCollection services)
  11. {
  12. // ...
  13. services.AddCap(x =>
  14. {
  15. x.UseMySql(opt=>{
  16. //MySqlOptions
  17. });
  18. // x.UseXXX ...
  19. });
  20. }
  21. ```
  22. ### 配置项
  23. NAME | DESCRIPTION | TYPE | DEFAULT
  24. :---|:---|---|:---
  25. TableNamePrefix | Cap表名前缀 | string | cap
  26. ConnectionString | 数据库连接字符串 | string | null
  27. ### 自定义表名称
  28. 你可以通过重写 `IStorageInitializer` 接口获取表名称的方法来做到这一点
  29. 示例代码:
  30. ```C#
  31. public class MyTableInitializer : MySqlStorageInitializer
  32. {
  33. public override string GetPublishedTableName()
  34. {
  35. //你的 发送消息表 名称
  36. }
  37. public override string GetReceivedTableName()
  38. {
  39. //你的 接收消息表 名称
  40. }
  41. }
  42. ```
  43. 然后将你的实现注册到容器中
  44. ```
  45. services.AddSingleton<IStorageInitializer, MyTableInitializer>();
  46. ```
  47. ## 使用事务发布消息
  48. ### ADO.NET
  49. ```csharp
  50. private readonly ICapPublisher _capBus;
  51. using (var connection = new MySqlConnection(AppDbContext.ConnectionString))
  52. {
  53. using (var transaction = connection.BeginTransaction(_capBus, autoCommit: false))
  54. {
  55. //your business code
  56. connection.Execute("insert into test(name) values('test')",
  57. transaction: (IDbTransaction)transaction.DbTransaction);
  58. _capBus.Publish("sample.rabbitmq.mysql", DateTime.Now);
  59. transaction.Commit();
  60. }
  61. }
  62. ```
  63. ### EntityFramework
  64. ```csharp
  65. private readonly ICapPublisher _capBus;
  66. using (var trans = dbContext.Database.BeginTransaction(_capBus, autoCommit: false))
  67. {
  68. dbContext.Persons.Add(new Person() { Name = "ef.transaction" });
  69. _capBus.Publish("sample.rabbitmq.mysql", DateTime.Now);
  70. dbContext.SaveChanges();
  71. trans.Commit();
  72. }
  73. ```