php - 数据库中的 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;
}
解决方案
推荐阅读
- android - Livedata观察者,等待onResume完成后再使用数据
- constraints - SPSS中的多重插补:算法如何处理预测变量的缺失值?
- google-apps-script - 如何从工作表中导入数据,其中工作表名称取决于单元格值
- java - 如何使用 ktor 获取客户端 IP
- python - Python 嵌套列表推导遍历两个列表元素
- jenkins - 仅当下游作业未在从属设备中运行时才触发 Jenkins 作业
- mysql - 如何优化连接三个表的 MySQL 查询
- javascript - 无法循环 json dict
- flutter - Flutter:我可以在 Dismissible 中使用 Ink 吗?
- python - 在Python中将json字典转换为数据框