开发文档 v2.x

读取/写入

更新时间:2024年4月4日 00:53 浏览:319

 

get - 读取

public function get(string $key)

参数:

  • string $key - 键名

返回值:

  • mixed | false - 不存在时返回 false

 

代码示例:

$product = Be::getCache()->get('product:xxx');

 

getMany - 批量读取

public function getMany(array $keys): array

参数:

  • array $keys - 键名数组

返回值:

  • array - 数量与键名数组一致

 

代码示例:

$arr = [
  'product:x',
  'product:xx',
  'product:xxx',
]

$products = Be::getCache()->getMany($arr);

 

set - 写入缓存

public function set(string $key, $value, int $expire = 0): bool

参数:

  • string $key - 键名
  • mixed $value
  • int $expire 有效时间(秒)

返回值:

  • bool - 是否写入成功

 

代码示例:

$product = [
  'id' => 'xxx',
  'name' => 'xxx',
  'price' => 100,
];

// 永久有效
Be::getCache()->set('product:xxx', $product );

// 有效期一天(即86400秒)
Be::getCache()->set('product:xxx', $product  86400);

 

setMany - 批量写入

public function setMany(array $keyValues, int $expire = 0): bool

参数:

  • string $keyValues - 键值对
  • int $expire 有效时间(秒)

返回值:

  • bool - 是否写入成功

 

代码示例:

$keyValues = [
  'product:x' => [
    'id' => 'x',
    'name' => 'x',
    'price' => 100,
    // ...
  ],
  'product:xx' => [
    'id' => 'xx',
    'name' => 'xx',
    'price' => 200,
    // ...
  ],
  'product:xxx' => [
    'id' => 'xxx',
    'name' => 'xxx',
    'price' => 300,
    // ...
  ],
  // ...
];

// 永久有效
Be::getCache()->setMany($keyValues);

// 有效期一天(即86400秒)
Be::getCache()->setMany($keyValues 86400);

 

setExpire - 设置超时时间

public function setExpire(string $key,  int $expire = 0): bool

参数:

  • string $key - 键名
  • int $expire 有效时间(秒)

返回值:

  • bool - 是否设置成功

 

代码示例:

// 有效期一天(即86400秒)
Be::getCache()->setExpire('product:xxx', 86400);

 

导航