<?php

namespace App\Model;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Redis;

class RedisModel extends Model
{
    private $WRITE_CONNECT_METHOD = ['set', 'del', 'rpush','lpush', 'expire', 'hset', 'hmset', 'hdel'];
    private $read = [];
    private $write = [];

    public function __construct($ConnectWrite = 'default', $ConnectRead = 'read')
    {
        parent::__construct();
        $this->read = Redis::connection($ConnectRead);
        $this->write = Redis::connection($ConnectWrite);
    }

    public function __call($method, $args)
    {
        if (in_array($method, $this->WRITE_CONNECT_METHOD)) {
            return $this->write->$method(...$args);
        } else {
            try {
                return $this->read->$method(...$args);
            } catch (ConnectionException $e) {
                return $this->write->$method(...$args);
            }
        }
    }

    //管道
    public function pipeline_to_hset($data){
        return $this->write->pipeline(function ($pipe) use ($data) {
            foreach ($data['data'] as $k => $v) {
                $pipe->hset($data['key'],$k,$v);
            }
        });
    }

}