0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Redisの導入と設定方法

Last updated at Posted at 2024-05-04

この記事では、Rack::Attackを使用するためのキャッシュストアとしてRedisを導入する手順について説明します。Redisは高速なインメモリデータストアであり、キャッシュやメッセージブローカーとして広く利用されています。

参考記事

Rack::Attackの使用については以下の記事を参照してください。

Redisのインストールと設定

  1. Redisのインストール:
    Redisは多くのOSで簡単にインストール可能です。以下はUbuntuとmacOSでのインストール方法です。

    • Ubuntu:

      sudo apt update
      sudo apt install redis-server
      
    • macOS (Homebrewを使用):

      brew install redis
      

    インストール後、Redisサーバーが自動的に起動するかを確認し、起動していない場合は手動で起動します。

    redis-server
    
  2. Redisの確認:
    インストールが成功したかどうかを確認するために、次のコマンドを実行してみます。正常に動作していれば、PONGという応答が返ってきます。

    redis-cli ping
    
  3. RailsでのRedis設定:
    RailsでRedisをキャッシュストアとして使用するには、まずredis gemが必要です。Gemfileに以下を追加し、bundle installを実行します。

    gem 'redis'
    

    次に、config/environments/development.rb(開発環境の設定)やconfig/environments/production.rb(本番環境の設定)にRedisをキャッシュストアとして指定します。

    config.cache_store = :redis_cache_store, { url: 'redis://localhost:6379/0' }
    

    このURLは、使用しているRedisサーバーの設定によります。ローカルで開発している場合はlocalhostを指定しますが、本番環境では適切なサーバーアドレスに変更してください。

Rack::AttackでのRedis利用

Rack::AttackがRedisを利用するように、config/initializers/rack_attack.rbにキャッシュストアの設定を追加します。

# 不要かもしれない
Rack::Attack.cache.store = ActiveSupport::Cache::RedisCacheStore.new(url: 'redis://localhost:6379/0')

この設定により、Rack::AttackはRedisを利用してIPアドレスやユーザーごとにリクエスト数を追跡し、設定したリミットを超えるリクエストを適切にブロックします。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?