FuelPHPのRedis_Dbを使ってみたのでメモ。
なにがしたいために使ってみたのか?
ですが、デイリーランキングを取り扱うために使ってみました。
ではRedisを使うための準備。
用意した環境は
CentOS7
redis version:3.9.102
です。
CentOS7にredisをインストールします。
1 2 3 4 |
$ yum install epel-release $ wget http://rpms.famillecollet.com/enterprise/remi-release-7.rpm $ rpm -Uvh remi-release-7*.rpm $ yum --enablerepo=remi,remi-test,epel install redis |
続いて、redisの設定ファイルを修正します。
とりあえずクローズ環境なので設定で接続IPをすべて開放します。
1 2 3 4 5 6 |
$ vi /etc/redis.conf bind 127.0.0.1 ↓ #bind 127.0.0.1 bind 0.0.0.0 |
ポートの穴あけもします。
1 2 3 4 |
$ firewall-cmd --list-all --zone=public $ firewall-cmd --add-port=6379/tcp --zone=public --permanent $ firewall-cmd --reload $ firewall-cmd --list-all --zone=public |
redisを起動します。
1 |
$ systemctl start redis.service |
ここまででredisの準備が完了です。
fuelphpの設定を行ないます。
fuel/app/config/db.php に設定追加します。
1 2 3 4 5 6 7 8 |
'redis' => array( 'default' => array( 'hostname' => 'xx.xx.xx.xx', // 接続先IP 'port' => 6379, 'timeout' => null, 'database' => 0, ), ), |
fuel/app/classes/controller/welcome.php を修正します。
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 |
class Controller_Welcome extends Controller { /** * The basic welcome message * * @access public * @return Response */ public function action_index() { // Redisに日別再生ランキングデータを追加 $redis = \Redis_Db::forge(); $redis->zincrby(date('Ymd'), '1', 'welcome'); // 第3引数はページ名とかを入れる return Response::forge(View::forge('welcome/index')); } public function get_dailyranking() { $this->format = 'json'; // Redisからデータを取得 $redis = \Redis_Db::forge(); // 日付、max、min [withscores]→スコアも取得 $data = $redis->zrevrangebyscore(date('Ymd'), '10', '1'); return $this->response($data , 200); } |
redisに保存されているかをチェックしてみます。
1 2 3 4 5 6 7 |
$ redis-cli 127.0.0.1:6379> ZREVRANGEBYSCORE 20170120 10 1 1) "welcome" 127.0.0.1:6379> ZREVRANGEBYSCORE 20170120 10 1 withscores 1) "welcome" 2) "1" |
/welcome/railyranking にアクセスしてみると
1 |
welcome |
が表示されると思います。
とりあえず簡単に実装できました。
あとはexpireとかを見直す必用があると思います。
参考サイト
http://fuelphp.jp/docs/1.7/classes/redis.html
http://redis.shibu.jp/commandreference/