简单实现ruby数据库加载和缓存加载

本文介绍了一种使用Ruby语言实现数据库加载和缓存加载的方法。通过ActiveRecord连接MySQL数据库,并利用Redis作为缓存存储,提高了数据访问效率。具体包括数据库连接配置、Redis缓存设置及数据读取流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

简单实现ruby数据库加载和缓存加载
2015-03-12 14
require 'active_record'
require 'redis-store'

ActiveRecord::Base.establish_connection(:adapter => "mysql2", :host => "<host>", :username => "<username>", :password => "<password>", :database => "db", :encoding => "utf8")

CACHE = ActiveSupport::Cache.lookup_store :redis_store, 'redis://127.0.0.1', {namespace: 'cache', expires_in: 300}

class RobotFilter < ActiveRecord::Base
#获取数据库链接
@robots = ActiveRecord::Base.connection.execute("select useragent, exclusion_useragent from robot_filters").collect { |e| [e[0].downcase, e[1].downcase] }
end

def eventinfo
#将查找放入缓存,如果已生成则直接读取。
return @eventinfo if self.instance_variable_defined? "@eventinfo"
@eventinfo = CACHE.fetch("Eventinfo:#{event_id}") { Eventinfo.find_by_id event_id }
end
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值