安装nuget包:
<PackageReference Include="DotNetCore.CAP" Version="6.0.0" />
<PackageReference Include="DotNetCore.CAP.Dashboard" Version="6.0.0" />
<PackageReference Include="DotNetCore.CAP.InMemoryStorage" Version="6.0.0" />
<PackageReference Include="DotNetCore.CAP.RabbitMQ" Version="6.0.0" />
<PackageReference Include="DotNetCore.CAP.SqlServer" Version="6.0.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0" />
配置program:
// CAP配置
builder.Services.AddCap(x =>
{
x.UseSqlServer("Server=.;Database=Blogging;Integrated Security=True"); // 生产环境应选择例如SQL Server, MySQL, MongoDB等
x.UseDashboard();//仪表板
// 添加事件总线cap
// 使用RabbitMQ进行事件中心处理
x.UseRabbitMQ(rb =>
{
rb.HostName = "localhost";
rb.UserName = "guest";
rb.Password = "guest";
rb.Port = 5672;
rb.VirtualHost = "/";
});
});
controller代码
using DotNetCore.CAP;
using Microsoft.AspNetCore.Mvc;
namespace WebApplication1.Controllers
{
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private readonly ICapPublisher _capPublisher;
public WeatherForecastController(ICapPublisher capPublisher)
{
_capPublisher = capPublisher;
}
[HttpPost]
public async Task<IActionResult> CreateUser([FromBody] User user)
{
// 创建用户逻辑...
var userCreatedEvent = new UserCreatedEvent
{
UserId = user.Id,
Name = user.Name
};
await _capPublisher.PublishAsync("user.created", userCreatedEvent);
return Ok();
}
[CapSubscribe("user.created")]
[NonAction]
public void OnUserCreated(UserCreatedEvent e)
{
// 处理用户创建事件,例如记录日志、发送邮件等
Console.WriteLine($"New user created: {e.UserId}, Name: {e.Name}");
}
}
public class User
{
public int Id { get; set; }
public string Name { get; set; }
}
}