Home Backend Development PHP Tutorial How CI framework (CodeIgniter) operates redis

How CI framework (CodeIgniter) operates redis

May 04, 2018 am 11:48 AM
codeigniter redis method

This article mainly introduces the CI framework (CodeIgniter) method of operating redis, and analyzes the related configuration and usage skills of the CodeIgniter framework for redis database operations. Friends in need can refer to the following

This article describes the examples CI framework (CodeIgniter) method of operating redis. Share it with everyone for your reference, the details are as follows:

1. Add the following configuration line to autoload.php

1

$autoload['libraries'] = array('redis');

Copy after login

2. In / Add the file redis.php

to application/config as follows:

1

2

3

4

5

6

7

8

9

<?php

// Default connection group

$config[&#39;redis_default&#39;][&#39;host&#39;] = &#39;localhost&#39;;   // IP address or host

$config[&#39;redis_default&#39;][&#39;port&#39;] = &#39;6379&#39;;     // Default Redis port is 6379

$config[&#39;redis_default&#39;][&#39;password&#39;] = &#39;&#39;;     // Can be left empty when the server does not require AUTH

$config[&#39;redis_slave&#39;][&#39;host&#39;] = &#39;&#39;;

$config[&#39;redis_slave&#39;][&#39;port&#39;] = &#39;6379&#39;;

$config[&#39;redis_slave&#39;][&#39;password&#39;] = &#39;&#39;;

?>

Copy after login

3. Add the file Redis to /application/libraries. php

File source: redis library file package

File content:

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

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

215

216

217

218

219

220

221

222

223

224

225

226

227

228

229

230

231

232

233

234

235

236

237

238

239

240

241

242

243

244

245

246

247

248

249

250

251

252

253

254

255

256

257

258

259

260

261

262

263

264

265

266

267

268

269

270

271

272

273

274

275

276

277

278

279

280

281

282

283

284

285

286

287

288

289

290

291

292

293

294

295

296

297

298

299

300

301

302

303

304

305

306

307

308

309

310

311

312

313

314

315

316

317

318

319

320

321

322

323

324

325

326

327

328

329

330

331

332

333

334

335

336

337

338

339

340

341

342

343

344

345

346

347

348

349

350

351

352

353

354

355

356

357

358

359

360

361

362

363

364

365

366

367

368

369

370

371

372

373

374

375

376

377

378

379

380

381

382

383

384

385

386

387

388

389

390

391

392

393

394

395

396

397

398

399

400

401

402

403

404

405

406

407

408

409

410

411

412

413

414

415

416

417

418

419

420

421

422

423

424

425

426

427

428

429

430

431

432

433

434

435

<?php defined(&#39;BASEPATH&#39;) OR exit(&#39;No direct script access allowed&#39;);

/**

 * CodeIgniter Redis

 *

 * A CodeIgniter library to interact with Redis

 *

 * @package     CodeIgniter

 * @category    Libraries

 * @author     Joël Cox

 * @version     v0.4

 * @link      https://github.com/joelcox/codeigniter-redis

 * @link      http://joelcox.nl

 * @license     http://www.opensource.org/licenses/mit-license.html

 */

class CI_Redis {

  /**

   * CI

   *

   * CodeIgniter instance

   * @var   object

   */

  private $_ci;

  /**

   * Connection

   *

   * Socket handle to the Redis server

   * @var   handle

   */

  private $_connection;

  /**

   * Debug

   *

   * Whether we&#39;re in debug mode

   * @var   bool

   */

  public $debug = FALSE;

  /**

   * CRLF

   *

   * User to delimiter arguments in the Redis unified request protocol

   * @var   string

   */

  const CRLF = "\r\n";

  /**

   * Constructor

   */

  public function __construct($params = array())

  {

    log_message(&#39;debug&#39;, &#39;Redis Class Initialized&#39;);

    $this->_ci = get_instance();

    $this->_ci->load->config(&#39;redis&#39;);

    // Check for the different styles of configs

    if (isset($params[&#39;connection_group&#39;]))

    {

      // Specific connection group

      $config = $this->_ci->config->item(&#39;redis_&#39; . $params[&#39;connection_group&#39;]);

    }

    elseif (is_array($this->_ci->config->item(&#39;redis_default&#39;)))

    {

      // Default connection group

      $config = $this->_ci->config->item(&#39;redis_default&#39;);

    }

    else

    {

      // Original config style

      $config = array(

        &#39;host&#39; => $this->_ci->config->item(&#39;redis_host&#39;),

        &#39;port&#39; => $this->_ci->config->item(&#39;redis_port&#39;),

        &#39;password&#39; => $this->_ci->config->item(&#39;redis_password&#39;),

      );

    }

    // Connect to Redis

    $this->_connection = @fsockopen($config[&#39;host&#39;], $config[&#39;port&#39;], $errno, $errstr, 3);

    // Display an error message if connection failed

    if ( ! $this->_connection)

    {

      show_error(&#39;Could not connect to Redis at &#39; . $config[&#39;host&#39;] . &#39;:&#39; . $config[&#39;port&#39;]);

    }

    // Authenticate when needed

    $this->_auth($config[&#39;password&#39;]);

  }

  /**

   * Call

   *

   * Catches all undefined methods

   * @param  string method that was called

   * @param  mixed  arguments that were passed

   * @return mixed

   */

  public function __call($method, $arguments)

  {

    $request = $this->_encode_request($method, $arguments);

    return $this->_write_request($request);

  }

  /**

   * Command

   *

   * Generic command function, just like redis-cli

   * @param  string full command as a string

   * @return mixed

   */

  public function command($string)

  {

    $slices = explode(&#39; &#39;, $string);

    $request = $this->_encode_request($slices[0], array_slice($slices, 1));

    return $this->_write_request($request);

  }

  /**

   * Auth

   *

   * Runs the AUTH command when password is set

   * @param  string password for the Redis server

   * @return void

   */

  private function _auth($password = NULL)

  {

    // Authenticate when password is set

    if ( ! empty($password))

    {

      // See if we authenticated successfully

      if ($this->command(&#39;AUTH &#39; . $password) !== &#39;OK&#39;)

      {

        show_error(&#39;Could not connect to Redis, invalid password&#39;);

      }

    }

  }

  /**

   * Clear Socket

   *

   * Empty the socket buffer of theconnection so data does not bleed over

   * to the next message.

   * @return NULL

   */

  public function _clear_socket()

  {

    // Read one character at a time

    fflush($this->_connection);

    return NULL;

  }

  /**

   * Write request

   *

   * Write the formatted request to the socket

   * @param  string request to be written

   * @return mixed

   */

  private function _write_request($request)

  {

    if ($this->debug === TRUE)

    {

      log_message(&#39;debug&#39;, &#39;Redis unified request: &#39; . $request);

    }

    // How long is the data we are sending?

    $value_length = strlen($request);

    // If there isn&#39;t any data, just return

    if ($value_length <= 0) return NULL;

    // Handle reply if data is less than or equal to 8192 bytes, just send it over

    if ($value_length <= 8192)

    {

      fwrite($this->_connection, $request);

    }

    else

    {

      while ($value_length > 0)

      {

        // If we have more than 8192, only take what we can handle

        if ($value_length > 8192) {

          $send_size = 8192;

        }

        // Send our chunk

        fwrite($this->_connection, $request, $send_size);

        // How much is left to send?

        $value_length = $value_length - $send_size;

        // Remove data sent from outgoing data

        $request = substr($request, $send_size, $value_length);

      }

    }

    // Read our request into a variable

    $return = $this->_read_request();

    // Clear the socket so no data remains in the buffer

    $this->_clear_socket();

    return $return;

  }

  /**

   * Read request

   *

   * Route each response to the appropriate interpreter

   * @return mixed

   */

  private function _read_request()

  {

    $type = fgetc($this->_connection);

    // Times we will attempt to trash bad data in search of a

    // valid type indicator

    $response_types = array(&#39;+&#39;, &#39;-&#39;, &#39;:&#39;, &#39;$&#39;, &#39;*&#39;);

    $type_error_limit = 50;

    $try = 0;

    while ( ! in_array($type, $response_types) && $try < $type_error_limit)

    {

      $type = fgetc($this->_connection);

      $try++;

    }

    if ($this->debug === TRUE)

    {

      log_message(&#39;debug&#39;, &#39;Redis response type: &#39; . $type);

    }

    switch ($type)

    {

      case &#39;+&#39;:

        return $this->_single_line_reply();

        break;

      case &#39;-&#39;:

        return $this->_error_reply();

        break;

      case &#39;:&#39;:

        return $this->_integer_reply();

        break;

      case &#39;$&#39;:

        return $this->_bulk_reply();

        break;

      case &#39;*&#39;:

        return $this->_multi_bulk_reply();

        break;

      default:

        return FALSE;

    }

  }

  /**

   * Single line reply

   *

   * Reads the reply before the EOF

   * @return mixed

   */

  private function _single_line_reply()

  {

    $value = rtrim(fgets($this->_connection));

    $this->_clear_socket();

    return $value;

  }

  /**

   * Error reply

   *

   * Write error to log and return false

   * @return bool

   */

  private function _error_reply()

  {

    // Extract the error message

    $error = substr(rtrim(fgets($this->_connection)), 4);

    log_message(&#39;error&#39;, &#39;Redis server returned an error: &#39; . $error);

    $this->_clear_socket();

    return FALSE;

  }

  /**

   * Integer reply

   *

   * Returns an integer reply

   * @return int

   */

  private function _integer_reply()

  {

    return (int) rtrim(fgets($this->_connection));

  }

  /**

   * Bulk reply

   *

   * Reads to amount of bits to be read and returns value within

   * the pointer and the ending delimiter

   * @return string

   */

  private function _bulk_reply()

  {

    // How long is the data we are reading? Support waiting for data to

    // fully return from redis and enter into socket.

    $value_length = (int) fgets($this->_connection);

    if ($value_length <= 0) return NULL;

    $response = &#39;&#39;;

    // Handle reply if data is less than or equal to 8192 bytes, just read it

    if ($value_length <= 8192)

    {

      $response = fread($this->_connection, $value_length);

    }

    else

    {

      $data_left = $value_length;

        // If the data left is greater than 0, keep reading

        while ($data_left > 0 ) {

        // If we have more than 8192, only take what we can handle

        if ($data_left > 8192)

        {

          $read_size = 8192;

        }

        else

        {

          $read_size = $data_left;

        }

        // Read our chunk

        $chunk = fread($this->_connection, $read_size);

        // Support reading very long responses that don&#39;t come through

        // in one fread

        $chunk_length = strlen($chunk);

        while ($chunk_length < $read_size)

        {

          $keep_reading = $read_size - $chunk_length;

          $chunk .= fread($this->_connection, $keep_reading);

          $chunk_length = strlen($chunk);

        }

        $response .= $chunk;

        // Re-calculate how much data is left to read

        $data_left = $data_left - $read_size;

      }

    }

    // Clear the socket in case anything remains in there

    $this->_clear_socket();

  return isset($response) ? $response : FALSE;

  }

  /**

   * Multi bulk reply

   *

   * Reads n bulk replies and return them as an array

   * @return array

   */

  private function _multi_bulk_reply()

  {

    // Get the amount of values in the response

    $response = array();

    $total_values = (int) fgets($this->_connection);

    // Loop all values and add them to the response array

    for ($i = 0; $i < $total_values; $i++)

    {

      // Remove the new line and carriage return before reading

      // another bulk reply

      fgets($this->_connection, 2);

      // If this is a second or later pass, we also need to get rid

      // of the $ indicating a new bulk reply and its length.

      if ($i > 0)

      {

        fgets($this->_connection);

        fgets($this->_connection, 2);

      }

      $response[] = $this->_bulk_reply();

    }

    // Clear the socket

    $this->_clear_socket();

    return isset($response) ? $response : FALSE;

  }

  /**

   * Encode request

   *

   * Encode plain-text request to Redis protocol format

   * @link  http://redis.io/topics/protocol

   * @param  string request in plain-text

   * @param  string additional data (string or array, depending on the request)

   * @return string encoded according to Redis protocol

   */

  private function _encode_request($method, $arguments = array())

  {

    $request = &#39;$&#39; . strlen($method) . self::CRLF . $method . self::CRLF;

    $_args = 1;

    // Append all the arguments in the request string

    foreach ($arguments as $argument)

    {

      if (is_array($argument))

      {

        foreach ($argument as $key => $value)

        {

          // Prepend the key if we&#39;re dealing with a hash

          if (!is_int($key))

          {

            $request .= &#39;$&#39; . strlen($key) . self::CRLF . $key . self::CRLF;

            $_args++;

          }

          $request .= &#39;$&#39; . strlen($value) . self::CRLF . $value . self::CRLF;

          $_args++;

        }

      }

      else

      {

        $request .= &#39;$&#39; . strlen($argument) . self::CRLF . $argument . self::CRLF;

        $_args++;

      }

    }

    $request = &#39;*&#39; . $_args . self::CRLF . $request;

    return $request;

  }

  /**

   * Info

   *

   * Overrides the default Redis response, so we can return a nice array

   * of the server info instead of a nasty string.

   * @return array

   */

  public function info($section = FALSE)

  {

    if ($section !== FALSE)

    {

      $response = $this->command(&#39;INFO &#39;. $section);

    }

    else

    {

      $response = $this->command(&#39;INFO&#39;);

    }

    $data = array();

    $lines = explode(self::CRLF, $response);

    // Extract the key and value

    foreach ($lines as $line)

    {

      $parts = explode(&#39;:&#39;, $line);

      if (isset($parts[1])) $data[$parts[0]] = $parts[1];

    }

    return $data;

  }

  /**

   * Debug

   *

   * Set debug mode

   * @param  bool  set the debug mode on or off

   * @return void

   */

  public function debug($bool)

  {

    $this->debug = (bool) $bool;

  }

  /**

   * Destructor

   *

   * Kill the connection

   * @return void

   */

  function __destruct()

  {

    if ($this->_connection) fclose($this->_connection);

  }

}

?>

Copy after login

4. Then you can This is used in

1

2

3

4

5

6

7

8

<?php

  if($this->redis->get(&#39;mark_&#39;.$gid) === null){ //如果未设置

    $this->redis->set(&#39;mark_&#39;.$gid, $giftnum); //设置

    $this->redis->EXPIRE(&#39;mark_&#39;.$gid, 30*60); //设置过期时间 (30 min)

  }else{

    $giftnum = $this->redis->get(&#39;mark_&#39;.$gid); //从缓存中直接读取对应的值

  }

?>

Copy after login

5. The key point is that what you need is explained in detail here

All the things you need to use The function only needs to be changed

1

$redis  ==> $this->redis

Copy after login

It should be noted that:

(1) You need to install the redis service locally (windows installation)
(2) and turn it on redis service
(3) Whether it is windows or linux, you need to install the redis extension of the corresponding version of PHP

Related recommendations:

How does the CI framework obtain the controller name and method name

Detailed explanation of CI framework integration smarty examples

The above is the detailed content of How CI framework (CodeIgniter) operates redis. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1655
14
PHP Tutorial
1253
29
C# Tutorial
1227
24
How to build the redis cluster mode How to build the redis cluster mode Apr 10, 2025 pm 10:15 PM

Redis cluster mode deploys Redis instances to multiple servers through sharding, improving scalability and availability. The construction steps are as follows: Create odd Redis instances with different ports; Create 3 sentinel instances, monitor Redis instances and failover; configure sentinel configuration files, add monitoring Redis instance information and failover settings; configure Redis instance configuration files, enable cluster mode and specify the cluster information file path; create nodes.conf file, containing information of each Redis instance; start the cluster, execute the create command to create a cluster and specify the number of replicas; log in to the cluster to execute the CLUSTER INFO command to verify the cluster status; make

How to clear redis data How to clear redis data Apr 10, 2025 pm 10:06 PM

How to clear Redis data: Use the FLUSHALL command to clear all key values. Use the FLUSHDB command to clear the key value of the currently selected database. Use SELECT to switch databases, and then use FLUSHDB to clear multiple databases. Use the DEL command to delete a specific key. Use the redis-cli tool to clear the data.

How to read redis queue How to read redis queue Apr 10, 2025 pm 10:12 PM

To read a queue from Redis, you need to get the queue name, read the elements using the LPOP command, and process the empty queue. The specific steps are as follows: Get the queue name: name it with the prefix of "queue:" such as "queue:my-queue". Use the LPOP command: Eject the element from the head of the queue and return its value, such as LPOP queue:my-queue. Processing empty queues: If the queue is empty, LPOP returns nil, and you can check whether the queue exists before reading the element.

How to configure Lua script execution time in centos redis How to configure Lua script execution time in centos redis Apr 14, 2025 pm 02:12 PM

On CentOS systems, you can limit the execution time of Lua scripts by modifying Redis configuration files or using Redis commands to prevent malicious scripts from consuming too much resources. Method 1: Modify the Redis configuration file and locate the Redis configuration file: The Redis configuration file is usually located in /etc/redis/redis.conf. Edit configuration file: Open the configuration file using a text editor (such as vi or nano): sudovi/etc/redis/redis.conf Set the Lua script execution time limit: Add or modify the following lines in the configuration file to set the maximum execution time of the Lua script (unit: milliseconds)

How to use the redis command line How to use the redis command line Apr 10, 2025 pm 10:18 PM

Use the Redis command line tool (redis-cli) to manage and operate Redis through the following steps: Connect to the server, specify the address and port. Send commands to the server using the command name and parameters. Use the HELP command to view help information for a specific command. Use the QUIT command to exit the command line tool.

How to set the redis expiration policy How to set the redis expiration policy Apr 10, 2025 pm 10:03 PM

There are two types of Redis data expiration strategies: periodic deletion: periodic scan to delete the expired key, which can be set through expired-time-cap-remove-count and expired-time-cap-remove-delay parameters. Lazy Deletion: Check for deletion expired keys only when keys are read or written. They can be set through lazyfree-lazy-eviction, lazyfree-lazy-expire, lazyfree-lazy-user-del parameters.

How to implement redis counter How to implement redis counter Apr 10, 2025 pm 10:21 PM

Redis counter is a mechanism that uses Redis key-value pair storage to implement counting operations, including the following steps: creating counter keys, increasing counts, decreasing counts, resetting counts, and obtaining counts. The advantages of Redis counters include fast speed, high concurrency, durability and simplicity and ease of use. It can be used in scenarios such as user access counting, real-time metric tracking, game scores and rankings, and order processing counting.

How to optimize the performance of debian readdir How to optimize the performance of debian readdir Apr 13, 2025 am 08:48 AM

In Debian systems, readdir system calls are used to read directory contents. If its performance is not good, try the following optimization strategy: Simplify the number of directory files: Split large directories into multiple small directories as much as possible, reducing the number of items processed per readdir call. Enable directory content caching: build a cache mechanism, update the cache regularly or when directory content changes, and reduce frequent calls to readdir. Memory caches (such as Memcached or Redis) or local caches (such as files or databases) can be considered. Adopt efficient data structure: If you implement directory traversal by yourself, select more efficient data structures (such as hash tables instead of linear search) to store and access directory information

See all articles