加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 使用api获取数据时,最好将数据存储在另一个数

发布时间:2020-12-16 21:07:14 所属栏目:百科 来源:网络整理
导读:参见英文答案 Caching calls to an external API in a rails app1个 我正在使用TMDB api来获取电影片名和发行年份等信息,但我想知道是否需要创建一个额外的数据库以便在本地存储所有这些信息,而不是继续使用api来获取信息?例如,我应该创建一个电影模型并致
参见英文答案 > Caching calls to an external API in a rails app1个
我正在使用TMDB api来获取电影片名和发行年份等信息,但我想知道是否需要创建一个额外的数据库以便在本地存储所有这些信息,而不是继续使用api来获取信息?例如,我应该创建一个电影模型并致电:
film.title

通过这样做访问存储在其上的标题的本地数据库,或者我打电话:

Tmdb::Movie.detail(550).title

并通过这样做再次呼叫api?

解决方法

处理了一个大型Rails应用程序,该应用程序调用了大约十几个其他应用程序,缓存是最好的选择.数据库解决方案的问题是使其保持最新.每次拨打电话的问题是它太慢了.有一个中间立场.为此你想要 Ruby on Rails Low Level Caching:

Sometimes you need to cache a particular value or query result instead of caching view fragments. Rails’ caching mechanism works great for storing any kind of information.

The most efficient way to implement low-level caching is using the Rails.cache.fetch method. This method does both reading and writing to the cache. When passed only a single argument,the key is fetched and value from the cache is returned. If a block is passed,the result of the block will be cached to the given key and the result is returned.

与您的用例相关的示例:

class TmdbService
  def self.movie_details(id)
    Rails.cache.fetch("tmdb.movie.details.#{id}",expires_in: 4.hours) do
      Tmdb::Movie.detail id
    end
end

然后,您可以将Rails应用程序配置为使用memcached或数据库用于缓存,这无关紧要.关键是您希望此缓存数据在某些时候到期,以确保您获取最新信息.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读