Cache.php 882 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. <?php
  2. namespace Biz\Db\Redis;
  3. class Cache {
  4. private $redis;
  5. function __construct() {
  6. try {
  7. $this->redis = C()->get('redis');
  8. if ($this->redis) {
  9. $this->redis = $this->redis->get();
  10. }
  11. } catch (\Exception $ex) {
  12. }
  13. }
  14. function checkRedis() {
  15. return $this->redis ? 1 : 0;
  16. }
  17. function get($key) {
  18. if (!$this->checkRedis()) {
  19. return;
  20. }
  21. return $this->redis->get($key);
  22. }
  23. function set($key, $value, $expire = 0) {
  24. if (!$this->checkRedis()) {
  25. return;
  26. }
  27. if ($expire > 0) {
  28. return $this->redis->setex($key, $value, $expire);
  29. }
  30. return $this->redis->set($key, $value);
  31. }
  32. //自动序列化
  33. function sets($key, $value, $expire = 0) {
  34. $value = json_encode($value);
  35. return $this->set($key, $value, $expire);
  36. }
  37. //自动序列化
  38. function gets($key) {
  39. $value = $this->get($key);
  40. return !$value ? null : json_decode($value, 1);
  41. }
  42. }