代码之家  ›  专栏  ›  技术社区  ›  Cryptex Technologies

如何从后端同步Redis服务器和Rails数据库?

  •  0
  • Cryptex Technologies  · 技术社区  · 7 年前

    我想加快Rails应用程序页面的加载时间,为此我正在使用Redis。我将查询记录从数据库存储到redis服务器。在这段代码中,我检查redis中是否已经存在变量。如果已经存在,则无需再次执行查询,否则执行查询。我已将过期时间设置为1小时,因此此redis变量将在1小时后重置。

    // Booths controller
    class BoothsController < ApplicationController
      def new_booth
        @booth_package_types = fetch_package_type
      end
    end
    
    // Booth helper
    module BoothsHelper
      def fetch_package_type
        package_types_booth =  $redis.get("package_types_booth") rescue nil
        if package_types_booth.nil?
          package_types_booth = PackageType.all.to_json
          $redis.set("package_types_booth", package_types_booth)
          $redis.expire("package_types_booth",1.hour.to_i)
        end
        @package_types_booth = JSON.load package_types_booth
      end
    end
    

    但这里的问题是,如果数据库中的记录在1小时前被更改,它将不会实时反映。Redis有没有解决方案可以在后端同步数据库和Redis服务器数据,我们不需要提过期时间?

    1 回复  |  直到 6 年前
        1
  •  1
  •   Mohammad Shahnawaz    6 年前

    class BoothsController < ApplicationController
      def new_booth
        @booth_package_types = fetch_package_type
      end
    end
    
    // Booth helper
    module BoothsHelper
      def fetch_package_type
        package_types_booth =  $redis.get("package_types_booth")
        if package_types_booth.nil?
          package_types_booth = PackageType.all.to_json
          $redis.set("package_types_booth", package_types_booth)
        end
        @package_types_booth = JSON.load package_types_booth
      end
    end
    
    #booth.rb file
    class Booth < ApplicationRecord
      after_save :clear_cache
    
      def clear_cache
        $redis.del "package_types_booth"
      end
    end