1. 程式人生 > >swoft操作redis、多例項配置

swoft操作redis、多例項配置

修改連線池配置

app/config/properties/cache.php 配置檔案


return [
    'redis'     => [
        'name'        => 'redis',
        'uri'         => [
            '127.168.88.88:6379'
        ],
        'minActive'   => 8,
        'maxActive'   => 8,
        'maxWait'     => 8,
        'maxWaitTime' => 3,
        'maxIdleTime' => 60,
        'timeout'     => 8,
        'db'          => 0,     // db改為0
        'prefix'      => '',    // 不需要字首
        'serialize'   => 0,
    ]
];

使用物件的方式操作redis

來到控制器

 /**
     * @Inject()
     * @var \Swoft\Redis\Redis
     */
    private $redis;

    public function testCache()
    {
        $result = $this->cache->set('name', 'stelin');
        $name   = $this->cache->get('name');

        $this->redis->incr("count");

        $this->redis->incrBy("count2", 2);

        return [$result, $name, $this->redis->get('count'), $this->redis->get('count2')];
    }

多例項Redis

配置一個Redis例項,需要新增一個例項連線池和連線池配置,然後通過bean,配置新增的redis例項
1、連線池配置

app/config/properties/cache.php 配置檔案裡新增:

    'demoRedis' => [
        'db'     => 0,
        'prefix' => '',
        'uri'         => [
            '127.168.99.99:6379'
        ],
    ],

因為上面我們修改了快取配置檔案,所以連線池配置檔案app/Pool/Config/DemoRedisPoolConfig.php

修改如下:

/**
 * DemoRedisPoolConfig
 *
 * @Bean()
 */
class DemoRedisPoolConfig extends RedisPoolConfig
{
    /**
     * @Value(name="${config.cache.demoRedis.db}", env="${REDIS_DEMO_REDIS_DB}")
     * @var int
     */
    protected $db = 0;

    /**
     * @Value(name="${config.cache.demoRedis.prefix}", env="${REDIS_DEMO_REDIS_PREFIX}")
     * @var string
     */
    protected $prefix = '';

    /**
     * @Value(name="${config.cache.demoRedis.uri}")
     * @var string
     */
    protected $uri = '';
}

2、配置Bean
config/beans/base.php

    'demoRedis' => [
        'class' => \Swoft\Redis\Redis::class,
        'poolName' => 'demoRedis'
    ]

注意這裡的poolName值和app/Pool/DemoRedisPool.php裡Pool的名稱一致。

3、使用新例項
使用@Inject,注入配置的redis例項,使用沒有任何區別,只是配置資訊發生了變化

/**
     * @Inject("demoRedis")
     * @var \Swoft\Redis\Redis
     */
    private $demoRedis;

    public function testDemoRedis()
    {
        $result = $this->demoRedis->set('name', 'swoft');
        $name   = $this->demoRedis->get('name');

        $this->demoRedis->incr('count');
        $this->demoRedis->incrBy('count2', 2);

        return [$result, $name, $this->demoRedis->get('count'), $this->demoRedis->get('count2'), '3'];
    }