Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 33 additions & 4 deletions src/Redis.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,14 @@ class Redis
public Client $client;
private string $type;
private int $score;
private string $hashKey;
private int $expire;

public function __construct(array $config = [])
{
$this->type = 'string';
$this->score = 0;
$this->hashKey = '';
$this->expire = -1;

$options = [
Expand Down Expand Up @@ -67,6 +69,18 @@ public function score(int $score): static
return $this;
}

/**
* 设置hash的key
*
* @return $this
*/
public function hashKey(string $key): static
{
$this->hashKey = $key;

return $this;
}

/**
* 设置过期时间.
*
Expand Down Expand Up @@ -97,19 +111,34 @@ public function remember(string $key, callable $callback): mixed
'get' => function () use ($key, $callback) {
$zset = $this->client->zrangebyscore($key, $this->score, $this->score);
if (is_array($zset) && count($zset) === 1) {
return json_decode(current($zset), true);
return current($zset);
}

// 没有匹配写入cache
$return = $callback();
$this->client->zadd($key, $this->score, json_encode($return));

$this->client->zadd($key, $this->score, $return);
return $return;
},
'put' => function ($value) use ($key): void {
$this->client->zadd($key, $this->score, json_encode($value));
$this->client->zadd($key, $this->score, $value);
},
],
'hash' => [
'get' => function () use ($callback, $key) {
$hash = $this->client->hget($key, $this->hashKey);
if ($hash) {
return $hash;
}

// 没有匹配写入cache
$return = $callback();
$this->client->hset($key, $this->hashKey, $return);
return $return;
},
'put' => function ($value) use ($key) {
$this->client->hset($key, $this->hashKey, $value);
}
]
];

$getType = (string) $this->client->type($key);
Expand Down
21 changes: 17 additions & 4 deletions tests/RedisTest.php
Original file line number Diff line number Diff line change
@@ -1,13 +1,26 @@
<?php

declare(strict_types=1);
it('remember', function () {
it('rememberZset', function () {
$response = redis()->type('zset')
->score(101)
->expire(3600)
->remember('test_name', function () {
return 'test101';
->remember('test_zset', function () {
return json_encode([
'name' => 'test101'
]);
});

expect($response)->toEqual('test101');
expect($response)->toEqual('{"name":"test101"}');
});

it('rememberHash', function () {
$response = redis()->type('hash')
->hashKey('business_uuid')
->expire(3600)
->remember('test_hash', function () {
return 'jqw4iej6uj48dw8';
});

expect($response)->toEqual('jqw4iej6uj48dw8');
});