123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109 |
- <?php
- namespace loyalsoft;
- /**
- * 对象字段将以hash表结构存入Redis中.
- * 以达到拆分读写各个子节点的目标, 最终能够节省(带宽、内存、运算)消耗,提升性能.
- * @author gwang
- * @version
- * 1.0.1 增加了一个stVer 记录存储次数. --gwang 2022.2.22
- * 1.0.0 创建. 2年以前就跟高健讨论过的理念,我一直没有落到实处(高健已经使用了). --gwang 2020.4.24
- */
- class HashSaver extends Object_ext {
- private $save_tag = array();
- /**
- * 添加回存记录
- * @param type $name
- */
- protected function save_tag($name) {
- $this->save_tag[] = $name;
- }
- /**
- * @return bool 是否需要回存
- */
- public function NeedSave(): bool {
- return count($this->save_tag) > 0;
- }
- /**
- * storeage version 存储版本(每写入一次+1)
- * @var int
- */
- public $stVer = 0;
- //
- // <editor-fold defaultstate="collapsed">
- /**
- * 自定义的数据加载方式
- * @param type $mem_key
- */
- function readDataFromMem($mem_key) {
- $ret = gMem()->hgetall($mem_key); # 已JSON解析
- if (null == $ret) {
- return $ret;
- }
- // my_Assert(null != $ret, ErrCode::err_mem); # 未找到数据
- $this->LoadFrom($ret);
- return $this;
- }
- /**
- * 全量存储数据到redis
- * @return boolean 是否成功
- */
- function updateDataFull($mem_key) {
- $this->stVer++;
- foreach ($this as $k => $v) {
- if ($k != 'save_tag') {
- $this->save_tag[] = $k;
- }
- }
- return gMem()->hmset_Cas($mem_key, $this);
- }
- /**
- * 转json
- * @return type
- */
- function toString() {
- if (false) { # 全量数据
- return parent::toString();
- } else { # 标记存储的数据
- $obj = new \stdClass();
- $obj->stVer = $this->stVer;
- foreach ($this->save_tag as $item) {
- $obj->$item = $this->$item;
- }
- return JsonUtil::encode($obj);
- }
- }
- /**
- * 转关联数组
- * @return type
- */
- function dic() {
- $newdic = ArrayInit();
- foreach ($this as $k => $v) {
- $newdic[$k] = msgpack_pack($v);
- }
- return $newdic;
- }
- /**
- * 存储数据到redis(这个设计目的是只保存改变的部分)
- * @version 2024.10.14 修复部分保存机制 --gwang
- * @version 2022.2.22 加入lua cas机制之后, 这个版本就已经弃用了. --gwang
- */
- function updateDataByTag($mem_key) {
- $this->stVer++;
- return gMem()->hmset_Cas($mem_key, $this);
- }
- // </editor-fold>
- }
|