首页 > 解决方案 > 数据库中的 Laravel 缓存冲突

问题描述

在将预订存储在数据库中之前,我正在使用 laravel 的 Cache 外观来构建预订数据。

我通过使用以下创建 UUID 的函数在缓存中生成预订,然后将其作为预订参考。

生成参考后,我将预订邮政编码设置如下

几乎所有其他预订都有冲突的邮政编码,这是缓存中另一个预订的邮政编码。

例如,当第一个客户来时,他们的邮政编码设置正确。第二个客户将设置他们的邮政编码,这会覆盖第一个客户的邮政编码,即使我使用的是唯一的预订参考。

缓存存储在数据库中

CACHE_DRIVER=database

BookingController.php

public function generateBooking() : JsonResponse
{
    return $this->respondSuccess([
        "booking_reference" => $this->booking->generate()
    ]);
}


public function setPostcode(string $bookingReference) : JsonResponse
{
    $booking = $this->booking->setReference($bookingReference)->get();

    $booking->setPostcode($this->request->postcode);
}

Booking.php

public function generate() : string
{
    $this->setReference(Uuid::generate(1));
    $this->store();
    return $this->reference();
}

public function setReference(string $reference)
{
    $this->reference = $reference;
    return $this;
}


public function reference() : string
{
    return $this->reference;
}


public function store($lastUpdated = true)
{
    if ($lastUpdated) {
        $this->lastUpdated = Carbon::now();
    }

    $expiresAt = now()->addMinutes(240);

    $bookingAsArray = $this->parser->toArray($this);

    Cache::put("bookings:".$this->reference(), $bookingAsArray, $expiresAt);
}


public function get() : Booking
{
    $booking = Cache::get("bookings:".$this->reference());

    return $this->parser->fromArray($this, $booking);
}


public function setPostcode($postcode, $shouldStore = true)
{
    $address = Address::make([
        "postcode" => $postcode
    ]);

    if ($this->address) {
        $address = $this->address;
        $address->postcode = $postcode;
    }

    $this->address = $address;

    if ($shouldStore) {
        $this->store();
    }
}

BookingParser.php

public function toArray(Booking $booking) : array
{
    $parsedBooking = [
        "reference" => $booking->reference()
    ];

    if ($booking->address()) {
        $parsedBooking["address"] = $booking->address()->toArray();
    }

    return $parsedBooking;
}

public function fromArray(Booking $booking, array $bookingArray) : Booking
{
    $booking->setReference($bookingArray["reference"], false);

    if (array_key_exists("address", $bookingArray)) {
        if (array_key_exists("postcode", $bookingArray["address"])) {
            $booking->setPostcode($bookingArray["address"]["postcode"], false);
        }
        $booking->setAddress($bookingArray["address"], false);
    }

    return $booking;
}

标签: phplaravelcaching

解决方案


推荐阅读