第18篇 .net使用RabbitMQ实现短信密码重置

在 C# 中使用 RabbitMQ 通过短信发送重置后的密码到用户的手机号上,你可以按照以下步骤进行

1.安装 RabbitMQ 客户端库

首先,确保你已经安装了 RabbitMQ 客户端库。你可以通过 NuGet 包管理器来安装:

dotnet add package RabbitMQ.Client

2.创建 RabbitMQ 连接和通道

创建一个 RabbitMQ 连接和通道,用于发送消息。

using RabbitMQ.Client;
using System;
using System.Text;

public class RabbitMQHelper
{
    private readonly string _hostName;
    private readonly string _userName;
    private readonly string _password;
    private readonly string _queueName;

public RabbitMQHelper(string hostName, string userName, string password, string queueName)
{
    _hostName = hostName;
    _userName = userName;
    _password = password;
    _queueName = queueName;
}

public void SendMessage(string message)
{
    var factory = new ConnectionFactory()
    {
        HostName = _hostName,
        UserName = _userName,
        Password = _password
    };

    using (var connection = factory.CreateConnection())
    using (var channel = connection.CreateModel())
    {
        channel.QueueDeclare(queue: _queueName,
                             durable: false,
                             exclusive: false,
                             autoDelete: false,
                             arguments: null);

        var body = Encoding.UTF8.GetBytes(message);

        channel.BasicPublish(exchange: "",
                             routingKey: _queueName,
                             basicProperties: null,
                             body: body);

        Console.WriteLine($" [x] Sent {message}");
    }
}
}

3.创建短信发送服务

创建一个短信发送服务,用于处理从 RabbitMQ 接收到的消息并发送短信。

public class SmsService
{
    public void SendSms(string phoneNumber, string message)
    {
        // 在这里实现短信发送逻辑
        Console.WriteLine($"Sending SMS to {phoneNumber}: {message}");
    }
}

4.创建 RabbitMQ 消费者

创建一个 RabbitMQ 消费者,用于从队列中接收消息并调用短信发送服务。

using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System;
using System.Text;

public class RabbitMQConsumer
{
private readonly string _hostName;
private readonly string _userName;
private readonly string _password;
private readonly string _queueName;
private readonly SmsService _smsService;

public RabbitMQConsumer(string hostName, string userName, string password, string queueName, SmsService smsService)
{
    _hostName = hostName;
    _userName = userName;
    _password = password;
    _queueName = queueName;
    _smsService = smsService;
}

public void StartConsuming()
{
    var factory = new ConnectionFactory()
    {
        HostName = _hostName,
        UserName = _userName,
        Password = _password
    };

    using (var connection = factory.CreateConnection())
    using (var channel = connection.CreateModel())
    {
        channel.QueueDeclare(queue: _queueName,
                             durable: false,
                             exclusive: false,
                             autoDelete: false,
                             arguments: null);

        var consumer = new EventingBasicConsumer(channel);
        consumer.Received += (model, ea) =>
        {
            var body = ea.Body.ToArray();
            var message = Encoding.UTF8.GetString(body);
            var phoneNumber = "user_phone_number"; // 从消息中解析出手机号
            _smsService.SendSms(phoneNumber, message);
        };

        channel.BasicConsume(queue: _queueName,
                             autoAck: true,
                             consumer: consumer);

        Console.WriteLine(" Press [enter] to exit.");
        Console.ReadLine();
    }
}
}

5.集成到用户密码重置流程

在你的用户密码重置流程中,生成新的密码并将其发送到 RabbitMQ 队列。

public class UserService
{
private readonly RabbitMQHelper _rabbitMQHelper;

public UserService(RabbitMQHelper rabbitMQHelper)
{
    _rabbitMQHelper = rabbitMQHelper;
}

public void ResetPassword(Guid userId)
{
    // 生成新的密码
    string newPassword = GeneratePassword();

    // 将新密码发送到 RabbitMQ 队列
    string message = $"Your new password is: {newPassword}";
    _rabbitMQHelper.SendMessage(message);

    // 其他逻辑,例如更新数据库中的密码
}

private string GeneratePassword()
{
    // 生成随机密码的逻辑
    return "random_password";
}
}

6.启动 RabbitMQ 消费者

在应用程序启动时,启动 RabbitMQ 消费者以处理消息。

public class Program
{
public static void Main(string[] args)
{
    string hostName = "localhost";
    string userName = "guest";
    string password = "guest";
    string queueName = "sms_queue";

    var smsService = new SmsService();
    var rabbitMQConsumer = new RabbitMQConsumer(hostName, userName, password, queueName, smsService);

    // 启动消费者
    rabbitMQConsumer.StartConsuming();
}
}

7.配置 RabbitMQ 连接信息

确保你的 RabbitMQ 连接信息(主机名、用户名、密码、队列名)是正确的,并且 RabbitMQ 服务器正在运行。

示例代码
以下是一个完整的示例代码,展示如何使用 RabbitMQ 通过短信发送重置后的密码到用户的手机号上:

using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System;
using System.Text;

public class RabbitMQHelper
{
private readonly string _hostName;
private readonly string _userName;
private readonly string _password;
private readonly string _queueName;

public RabbitMQHelper(string hostName, string userName, string password, string queueName)
{
    _hostName = hostName;
    _userName = userName;
    _password = password;
    _queueName = queueName;
}

public void SendMessage(string message)
{
    var factory = new ConnectionFactory()
    {
        HostName = _hostName,
        UserName = _userName,
        Password = _password
    };

    using (var connection = factory.CreateConnection())
    using (var channel = connection.CreateModel())
    {
        channel.QueueDeclare(queue: _queueName,
                             durable: false,
                             exclusive: false,
                             autoDelete: false,
                             arguments: null);

        var body = Encoding.UTF8.GetBytes(message);

        channel.BasicPublish(exchange: "",
                             routingKey: _queueName,
                             basicProperties: null,
                             body: body);

        Console.WriteLine($" [x] Sent {message}");
    }
}
}

public class SmsService
{
public void SendSms(string phoneNumber, string message)
{
    // 在这里实现短信发送逻辑
    Console.WriteLine($"Sending SMS to {phoneNumber}: {message}");
}
}

public class RabbitMQConsumer
{
private readonly string _hostName;
private readonly string _userName;
private readonly string _password;
private readonly string _queueName;
private readonly SmsService _smsService;

public RabbitMQConsumer(string hostName, string userName, string password, string queueName, SmsService smsService)
{
    _hostName = hostName;
    _userName = userName;
    _password = password;
    _queueName = queueName;
    _smsService = smsService;
}

public void StartConsuming()
{
    var factory = new ConnectionFactory()
    {
        HostName = _hostName,
        UserName = _userName,
        Password = _password
    };

    using (var connection = factory.CreateConnection())
    using (var channel = connection.CreateModel())
    {
        channel.QueueDeclare(queue: _queueName,
                             durable: false,
                             exclusive: false,
                             autoDelete: false,
                             arguments: null);

        var consumer = new EventingBasicConsumer(channel);
        consumer.Received += (model, ea) =>
        {
            var body = ea.Body.ToArray();
            var message = Encoding.UTF8.GetString(body);
            var phoneNumber = "user_phone_number"; // 从消息中解析出手机号
            _smsService.SendSms(phoneNumber, message);
        };

        channel.BasicConsume(queue: _queueName,
                             autoAck: true,
                             consumer: consumer);

        Console.WriteLine(" Press [enter] to exit.");
        Console.ReadLine();
    }
}
}

public class UserService
{
private readonly RabbitMQHelper _rabbitMQHelper;

public UserService(RabbitMQHelper rabbitMQHelper)
{
    _rabbitMQHelper = rabbitMQHelper;
}

public void ResetPassword(Guid userId)
{
    // 生成新的密码
    string newPassword = GeneratePassword();

    // 将新密码发送到 RabbitMQ 队列
    string message = $"Your new password is: {newPassword}";
    _rabbitMQHelper.SendMessage(message);

    // 其他逻辑,例如更新数据库中的密码
}

private string GeneratePassword()
{
    // 生成随机密码的逻辑
    return "random_password";
}
}

public class Program
{
public static void Main(string[] args)
{
    string hostName = "localhost";
    string userName = "guest";
    string password = "guest";
    string queueName = "sms_queue";

    var smsService = new SmsService();
    var rabbitMQConsumer = new RabbitMQConsumer(hostName, userName, password, queueName, smsService);

    // 启动消费者
    rabbitMQConsumer.StartConsuming();
}
}
posted @ 2024-09-08 11:54  似梦亦非梦  阅读(153)  评论(0编辑  收藏  举报