所有
我正在尝试使用缓存来避免在针对特定区域发出请求时通过http进行请求。
例如,你在洛杉矶,你身边的3个人(appx 1英里)对附近的加油站进行谷歌搜索。
不是每次都要求,而是允许与您亲近并进行相同搜索的人更快地获得已缓存的结果。
在之前的方法中,我使用Redis进行缓存并使用参数构建密钥,但要重新使用它,您需要完全匹配,因为创建的密钥基于" 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,当给出一个坐标和距离时,它会给我一个lat / lon的范围
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中的位置是否在"区域内#34;
现在的问题是将此逻辑连接到Redis并使用它来重新使用缓存。
最好应该是生成一个Redis密钥并查找它,但这并不容易,因为我不想解析存储的每个密钥,并逐个检查定义的lat / lon params以查看是否匹配已知的位置范围。
答案 0 :(得分:0)
gem 'redis'
运行捆绑安装
default: &default
host: localhost
port: 6379
db: 15
development:
<<: *default
test:
<<: *default
production:
<<: *default
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变量,因为初始化程序文件是在app load上加载的。
REDIS.set("gas_station__#{some_location}", latitude_values here)
REDIS.get("gas_station_#{some_location}")