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'];
    }

猜你喜欢

转载自blog.csdn.net/github_26672553/article/details/82831897