C# 简单Redis抢票功能

确保引用了StackExchange.Redis库

using StackExchange.Redis;
using System;
using System.Threading;

class Program
{
    static void Main(string[] args)
    {
        ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("localhost");
        IDatabase db = redis.GetDatabase();

        int totalSeats = 10;
        int availableSeats;

        while (true)
        {
            // 获取当前可用座位数
            availableSeats = totalSeats - (int)db.HashLength("reservations");

            if (availableSeats <= 0)
            {
                Console.WriteLine("对不起,座位已满!");
                break;
            }

            Console.WriteLine($"当前可用座位数:{availableSeats}");

            Thread[] threads = new Thread[availableSeats];
            for (int i = 0; i < availableSeats; i++)
            {
                int seatNumber = i + 1;
                threads[i] = new Thread(() => TryReserveSeat(db, seatNumber));
                threads[i].Start();
            }

            foreach (var thread in threads)
            {
                thread.Join();
            }
        }

        redis.Close();
    }

    static void TryReserveSeat(IDatabase db, int seatNumber)
    {
        string username = Guid.NewGuid().ToString(); // 使用随机用户名
        string seatKey = $"seat{seatNumber}";

        if (db.HashExists("reservations", seatKey))
        {
            Console.WriteLine($"座位{seatNumber}已经被预订!");
        }
        else
        {
            if (db.HashSet("reservations", username, seatKey))
            {
                Console.WriteLine($"座位{seatNumber}由用户{username}预订成功!");
            }
            else
            {
                Console.WriteLine($"座位{seatNumber}预订失败!");
            }
        }
    }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值