zf2 redis 练手2

本文详细阐述了如何优化Redis的配置与实例化过程,通过将配置分离到全局配置文件中,减少代码耦合,提高代码可维护性。具体包括启动Redis服务、调整配置参数并实现在需要使用Redis的模块中获取和操作Redis实例的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. 接着上文,不可能每次都都去实例化redis,这很麻烦,而且redis的配置没有分离,这样耦合度很高,不利于后续的代码修改,所以有修改了。

  2. 首先还是要启动redis-server,

  3. 在global.php


  4. ?
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
       return  array (
          'redis_config' => array (
             'Server'    => '127.0.0.1:6379' ,
             'Database'     => '0' ,
             'Namespace' => 'session' ,
             'Writable'  =>true,
             'Readable'  =>true,
             ),
     
         'service_manager'  =>  array (
                 'factories'  =>  array (
                     'Zend\Db\Adapter\Adapter\Redis'  =>  function  ( $sm ) {
                        $config  $sm ->get( 'Configuration' );
                        if (isset( $config [ 'redis_config' ])){
                            //redis option
                        $config_redis  $config [ 'redis_config' ];
                        $redisOption  new  \Zend\Cache\Storage\Adapter\RedisOptions();
                        $redisOption ->setServer( $config_redis [ 'Server' ])
                            ->setDatabase( $config_redis [ 'Database' ])
                            ->setNamespace( $config_redis [ 'Namespace' ])
                            ->setWritable( $config_redis [ 'Writable' ])
                            ->setReadable( $config_redis [ 'Readable' ]);
                            return  new  \Zend\Cache\Storage\Adapter\Redis( $redisOption )
                        }
                     },
                 ),
             ),
    );

    之后在调用的地方

  5. ?
    1
    2
    3
    4
    5
    6
    7
      public  function  redisAction()
         {
             //获取redis
             $redis  $this ->getServiceLocator()->get( 'Zend\Db\Adapter\Adapter\Redis' );
             $redis ->setItem( 'zzc' 'zhangzhican110@gmail.com' );
             die ;
         }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值