HashSaver.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. <?php
  2. namespace loyalsoft;
  3. /**
  4. * 对象字段将以hash表结构存入Redis中.
  5. * 以达到拆分读写各个子节点的目标, 最终能够节省(带宽、内存、运算)消耗,提升性能.
  6. * @author gwang
  7. * @version
  8. * 1.0.1 增加了一个stVer 记录存储次数. --gwang 2022.2.22
  9. * 1.0.0 创建. 2年以前就跟高健讨论过的理念,我一直没有落到实处(高健已经使用了). --gwang 2020.4.24
  10. */
  11. class HashSaver extends Object_ext {
  12. private $save_tag = array();
  13. /**
  14. * 添加回存记录
  15. * @param type $name
  16. */
  17. protected function save_tag($name) {
  18. $this->save_tag[] = $name;
  19. }
  20. /**
  21. * @return bool 是否需要回存
  22. */
  23. public function NeedSave(): bool {
  24. return count($this->save_tag) > 0;
  25. }
  26. /**
  27. * storeage version 存储版本(每写入一次+1)
  28. * @var int
  29. */
  30. public $stVer = 0;
  31. //
  32. // <editor-fold defaultstate="collapsed">
  33. /**
  34. * 自定义的数据加载方式
  35. * @param type $mem_key
  36. */
  37. function readDataFromMem($mem_key) {
  38. $ret = gMem()->hgetall($mem_key); # 已JSON解析
  39. if (null == $ret) {
  40. return $ret;
  41. }
  42. // my_Assert(null != $ret, ErrCode::err_mem); # 未找到数据
  43. $this->LoadFrom($ret);
  44. return $this;
  45. }
  46. /**
  47. * 存储数据到redis
  48. * @return boolean 是否成功
  49. */
  50. function updateDataFull($mem_key) {
  51. $this->stVer++;
  52. return gMem()->hmset_Cas($mem_key, $this);
  53. // return true;
  54. // return gMem()->hmset($mem_key, $this);
  55. }
  56. function dic() {
  57. $newdic = ArrayInit();
  58. foreach ($this as $k => $v) {
  59. $newdic[$k] = msgpack_pack($v);
  60. }
  61. return $newdic;
  62. }
  63. /**
  64. * 存储数据到redis(这个设计目的是只保存改变的部分)
  65. */
  66. function updateDataByTag($mem_key) {
  67. $data = array();
  68. foreach (self::$save_tag as $k) {
  69. $data[$k] = $this->$k;
  70. }
  71. $this->stVer++;
  72. $data['stVer'] = $this->stVer;
  73. return gMem()->hmset($mem_key, $data);
  74. }
  75. // </editor-fold>
  76. }