MassTransit 的官网地址:
快速使用版链接: https://masstransit.io/quick-starts/amazon-sqs
-
Login to AWS
-
Create a User with Access key - Programmatic access 1. Grant the user the Sample IAM Policy below
(注意:其中有AWS SQS 和 AWS SNS 权限)**
{ "Version": "2012-10-17", "Statement": [ { "Sid": "SqsAccess", "Effect": "Allow", "Action": [ "sqs:SetQueueAttributes", "sqs:ReceiveMessage", "sqs:CreateQueue", "sqs:DeleteMessage", "sqs:SendMessage", "sqs:GetQueueUrl", "sqs:GetQueueAttributes", "sqs:ChangeMessageVisibility", "sqs:PurgeQueue", "sqs:DeleteQueue", "sqs:TagQueue" ], "Resource": "arn:aws:sqs:*:YOUR_ACCOUNT_ID:*" },{ "Sid": "SnsAccess", "Effect": "Allow", "Action": [ "sns:GetTopicAttributes", "sns:CreateTopic", "sns:Publish", "sns:Subscribe" ], "Resource": "arn:aws:sns:*:YOUR_ACCOUNT_ID:*" },{ "Sid": "SnsListAccess", "Effect": "Allow", "Action": [ "sns:ListTopics" ], "Resource": "*" } ] }
Add the MassTransit.AmazonSQS package to the project.
$ dotnet add package MassTransit.AmazonSQS
Edit Program.cs
Change UsingInMemory to UsingAmazonSQS
public override void ConfigureServices(ServiceConfigurationContext context)
{
context.Services.AddMassTransit(x =>
{
//添加 实现了 IConsumer 接口的类
x.AddConsumer<RegisterConsumer>();
x.UsingAmazonSqs((context, cfg) =>
{
cfg.Host("us-east-1", h => {
h.AccessKey("your-iam-access-key"); //替换你AWS的Access key
h.SecretKey("your-iam-secret-key"); //替换你AWS的secret key
});
cfg.ConfigureEndpoints(context);
});
});
services.AddHostedService<Worker>();
});
}
RegisterConsumer类
public class LoginDto
{
public string UserName { get; set; }
}
public class RegisterConsumer : IConsumer<LoginDto>
{
private readonly IRegstrationRepository _regstrationRepository;
private readonly IObjectMapper _objectMapper;
public RegisterConsumer(IRegstrationRepository regstrationRepository, IObjectMapper objectMapper)
{
_objectMapper = objectMapper;
_regstrationRepository = regstrationRepository;
}
//接收AWS SQS消息。
public Task Consume(ConsumeContext<LoginDto> context)
{
return _regstrationRepository.CreateUserAsync(_objectMapper.Map<LoginDto, Login>(context.Message));
}
}
(测试)后台服务 Worker :
public class Worker : BackgroundService
{
readonly IBus _bus;
public Worker(IBus bus)
{
_bus = bus;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
//循环发布消息
while (!stoppingToken.IsCancellationRequested)
{
await _bus.Publish(new LoginDto{ UserName = ”admin“ }, stoppingToken);
}
}
至此Asp.net core 连接AWS SQS已经完成!