ruby-on-rails - 根据位置创建缓存键

标签 ruby-on-rails ruby caching redis

全部,

当针对特定区域发出请求时,我正在尝试使用缓存来避免通过 http 请求。

例如,您在洛杉矶,您周围的 3 个人(大约 1 英里)在 google 上搜索附近的加油站。

与其每次都请求,不如让与您关系密切并进行相同搜索的人获得已缓存的结果更快。

在以前的方法中,我使用 Redis 进行缓存并使用参数构建 key ,但要重新使用它,您需要完全匹配,因为创建的 key 基于“gas_station__”

 def set_cache key, val
    return if blank?( key ) || blank?( val )

    connection.set key, val
    connection.expire key, EXPIRY
  end

  def get_cache key
    connection.get( key ) if present?( key )
  end

现在我已经使用了 Ruby Gem geocode api,当给出坐标和距离时,它会返回一个纬度/经度范围

  Geocoder::Calculations.bounding_box(location, distance)

并使用下面的 api:

def isLocationInRange(location, area)
  if location[0].between?(area[0], area[2]) && location[1].between?(area[1], area[3])
    return true
  end
  false
end

我能够知道 isLocationInRange 中给出的位置是否在“区域”内

现在的问题是将此逻辑连接到 Redis 并使用它来重新使用缓存。

最好的办法是生成一个 Redis 键并查找它,但这并不容易,因为我不想解析存储的每个键并一个一个地检查定义的纬度/经度参数以查看是否匹配已知范围位置。

最佳答案

gem 文件

gem 'redis'

运行捆绑安装

配置/redis.yml

default: &default
  host: localhost
  port: 6379
  db: 15

development:
  <<: *default

test:
  <<: *default

production:
  <<: *default

config/initializers/redis.rb

redis_config = HashWithIndifferentAccess.new(Rails.application.config_for(:redis))
REDIS = Redis.new(host: redis_config[:host], port: redis_config[:port], db: redis_config[:db])

现在 REDIS 变量在整个应用程序中可用,因为初始化程序文件是在应用程序加载时加载的。

REDIS.set("gas_station__#{some_location}", latitude_values here)
REDIS.get("gas_station_#{some_location}")

引用文献:https://github.com/redis/redis-rb

关于ruby-on-rails - 根据位置创建缓存键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41581179/

相关文章:

java - 如何填充缓存并保持更新

javascript - 在 jQuery 中访问 Rails.env 变量?

ruby-on-rails - 重定向到另一个 Controller 中的 SHOW 操作

ruby - Ruby 有哪些绘图包/API?

azure - 在 Azure 云服务辅助角色中使用本地内存进行缓存

java - 使用键和值的软引用实现缓存

ruby-on-rails - rails : Is there an equivalent to save_without_validation which skips after_save filters?

ruby-on-rails - group_by 相对日期范围

ruby-on-rails - form_for - 生成唯一的 id

ruby-on-rails - 替换 URI.escape 以避免 Lint/UriEscapeUnescape 警告?