第18篇 .net使用RabbitMQ實現簡訊密碼重置

似梦亦非梦發表於2024-09-08

在 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();
}
}

相關文章