RedisService.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. <?php
  2. namespace RedisBundle\Services;
  3. use Predis\Client as Redis;
  4. class RedisService extends Redis implements CollectorInterface
  5. {
  6. public function setOptions($options)
  7. {
  8. $this->options = $this->createOptions($options ?: array());
  9. $this->profile = $this->options->profile;
  10. }
  11. public function setConnection($parameters)
  12. {
  13. $this->connection = $this->createConnection($parameters ?: array());
  14. }
  15. /**
  16. * @param string $key
  17. * @return array
  18. */
  19. public function get($key, $output = false)
  20. {
  21. $start = microtime(true);
  22. $_data = parent::get($key);
  23. $end = microtime(true);
  24. $t = $end - $start;
  25. if ($output) {
  26. print_r("REDIS GET key '{$key}': {$t} segundos" . PHP_EOL);
  27. }
  28. $start = microtime(true);
  29. $data_cached = json_decode($_data, true);
  30. $end = microtime(true);
  31. $t = $end - $start;
  32. if ($output) {
  33. print_r("DECODE key '{$key}': {$t} segundos" . PHP_EOL);
  34. }
  35. parent::disconnect();
  36. parent::quit();
  37. if (is_null($data_cached)) $data_cached = array();
  38. return $data_cached;
  39. }
  40. /**
  41. * @param string $key
  42. * @param array $data
  43. */
  44. public function set($key, $data, $output = false)
  45. {
  46. $start = microtime(true);
  47. $_save = json_encode($data);
  48. $end = microtime(true);
  49. $t = $end - $start;
  50. if ($output) {
  51. print_r("ENCODE key '{$key}': {$t} segundos" . PHP_EOL);
  52. }
  53. $start = microtime(true);
  54. parent::setex($key, 3600, $_save);
  55. $end = microtime(true);
  56. $t = $end - $start;
  57. if ($output) {
  58. print_r("SETEX key '{$key}': {$t} segundos" . PHP_EOL);
  59. }
  60. }
  61. /**
  62. * @param string $key
  63. * @return string
  64. */
  65. public function getString($key, $output = false)
  66. {
  67. $start = microtime(true);
  68. $_data = parent::get($key);
  69. $end = microtime(true);
  70. $t = $end - $start;
  71. if ($output) {
  72. print_r("REDIS GET key '{$key}': {$t} segundos" . PHP_EOL);
  73. }
  74. parent::disconnect();
  75. parent::quit();
  76. return $_data;
  77. }
  78. /**
  79. * @param string $key
  80. * @param string $data
  81. */
  82. public function setString($key, $data, $output = false)
  83. {
  84. $_save = $data;
  85. $start = microtime(true);
  86. parent::setex($key, 3600, $_save);
  87. $end = microtime(true);
  88. $t = $end - $start;
  89. if ($output) {
  90. print_r("SETEX key '{$key}': {$t} segundos" . PHP_EOL);
  91. }
  92. }
  93. }