用redis的方式缓存了很多的code如何判断是否在里面
时间: 2024-03-08 13:45:48 浏览: 21
在 Redis 中缓存了很多的 `code` 值后,可以使用 Redis 提供的 `sismember` 方法判断指定的 `code` 是否在缓存中。以下是一种实现方式:
```
use Illuminate\Support\Facades\Redis;
function isCodeInCache($code) {
$key = 'source_codes';
return Redis::sismember($key, $code);
}
```
在上述代码中,使用 `Redis::sismember` 方法判断指定的 `code` 是否在 Redis 的 `source_codes` 集合中。如果在集合中,该方法会返回 `1`,否则返回 `0`。
需要注意的是,使用 `sismember` 方法判断 `code` 是否在集合中时,要求集合中存储的数据类型必须为字符串。因此,在将 `code` 值添加到集合中时,应该将其转换为字符串类型。例如:
```
use Illuminate\Support\Facades\Redis;
use App\Models\Source;
function cacheAllCodes() {
$key = 'source_codes';
$sources = Source::where('is_close', 0)->select('code')->get();
$codes = $sources->pluck('code')->toArray();
Redis::sadd($key, ...$codes);
Redis::expire($key, 2592000);//30天
}
```
在上述代码中,使用 `Redis::sadd` 方法将所有的 `code` 值添加到 Redis 的 `source_codes` 集合中,并使用 `Redis::expire` 方法设置集合的过期时间为 2592000 秒(30 天)。这样,在调用 `isCodeInCache` 函数时,就可以判断指定的 `code` 是否在集合中了。
相关推荐
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)