gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 11:30:13 24 4
gpt4 key购买 nike

全部,

当针对特定区域发出请求时,我正在尝试使用缓存来避免通过 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com