`
xxj
  • 浏览: 421156 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

cached_model 简介

阅读更多
数据库是瓶颈,今天我们介绍model级别的cache。Cached Model 是一个简单的只对单记录做缓存的plugin.Cached Model的的存储分为本地存储和Memcached存储。本地存储大家都知道,一般都是用Hash来存储的。这里的Memcached是一种网络分布式存储。

我们先来看看如果应用cached model
一:安装
gem install cached_model -y
二:应用
简单的创建一个工程
rails cached_model_demo
新建Page
ruby script/generate scaffold_resource page title:string content:text created_at:timestamp
创建数据库
rake db:migrate
修改Page Model,继承CachedModel
class Page < CachedModel
end
在enviroment中增加memcached的配置的代码:
require 'cached_model'

memcache_options = {
  :c_threshold => 10_000,
  :compression => true,
  :debug => false,
  :namespace => 'cached_model_demo',
  :readonly => false,
  :urlencode => false
}

CACHE = MemCache.new memcache_options
CACHE.servers = 'localhost:11211'
上面都是一些简单的东西,我们就忽略了,有什么问题,大家提出来。

好了,准备就绪。cached_model 默认是采用memcached store的方式,当然你可以采用local的方式
CachedModel::use_local_cache=true
启动memcached server
memcached -vv
我们传递vv参数可以查看更多的日志信息,具体的可以查看--help


打开ruby script/console 并打开tail -f log/development.log查看日志
新建page
Page.create :title=>'Hello World'
Page.create :title=>'Hello World Again'
成功。cached_model只覆盖了ActiveRecord的两个方法,一个是find,一个是find_by_sql.我们具体的分析一下这两个方法
1:) find
 def self.find(*args)
        args[0] = args.first.to_i if args.first =~ /\A\d+\Z/
        # Only handle simple find requests.  If the request was more complicated,
        # let the base class handle it, but store the retrieved records in the
        # local cache in case we need them later.        
        if args.length != 1 || !Fixnum === args.first then
            # Rails requires multiple levels of indirection to look up a record
            # First call super
            records = super
            # Then, if it was a :all, just return
            return records if args.first == :all
            return records if RAILS_ENV == 'test'
            case records
            when Array then
                records.each { |r| r.cache_store }
            end
            return records
        end

        return super
    end
这里面压根没有读取cache的代码,不管这么样,都会先调用super执行查询,只有在
>参数个数不为1或第一个不是数字
>第一个参数不是:all
>不是test环境下
>返回结果为Array的时候才缓存model   
也就是说基本没什么作用。
我们试验下
Page.find 1

依然执行SQL,memcached无反应

Page.find 1,2
我们会看到memcached中有了两条记录
<1924 new client connection
<1924 set cached_model_demo:active_record:Page:1 0 900 95
>1924 STORED
<1924 set cached_model_demo:active_record:Page:2 0 900 101
>1924 STORED
保存了两条记录

在执行
Page.find 1
依然查询数据库。那我们该如何取这样的数据呢?
>> Cache.get "active_record:Page:1"
=> #"Hello World", "id"=>"1", "content"=>nil, "cr
ed_at"=>"2007-11-10 18:29:29"}>
2:)find_by_sql
 def self.find_by_sql(*args)
        return super unless args.first =~ /^SELECT \* FROM #{table_name} WHERE \(?#{table_name}\.#{primary_key} = '?(\d+)'?\)? +LIMIT 1/
很简单,但是他只cache根据主键id查询的record
Page.find_by_sql "SELECT * FROM PAGES WHERE PAGES.ID = 1 LIMIT 1"
<1924 get cached_model_demo:active_record:Page:1
>1924 sending key cached_model_demo:active_record:Page:1
>1924 END
development.log无SQL查询
MemCache Get (0.000000)  active_record:Page:1



这里取回的是我们刚才执行Page.find 1,2,缓存1的数据,如果没有,则会存储该数据,下次再查询直接从cache中获取。

三:更新
当该id的记录update,destroy都会更新cache,这个没什么好说的。

四:改进
这些功能太过于简单了,我们可以稍微对源码做点修改
一:缓存Page.find 的单条记录
if CachedModel.use_memcache?
        record = Cache.get "active_record:#{name}:#{args.first}"

        #return cached model
        return record unless record.nil?
        #call super find
        record = super
        #store in memcache
        record.cache_store

        return record
      end
    end


二:find_by_sql的改进,空格,大小写必须一致才能生效
这条正则表达式太过于简单,我们可以稍微修改
1:) 忽略大小写 /i
2:) 忽略table的名称,只需要id=?几匹配
2;) 忽略空格


警告:
对于有关联的Model请谨慎使用cached_model,建议不使用。
分享到:
评论
1 楼 yangzhihuan 2009-06-15  
能否提供一下 cached model  的下载地址吗?
这个名字太普遍了,都不知道那个是那个了.

相关推荐

    关于Django外键赋值问题详解

    本文主要给大家介绍关于Django外键赋值的相关内容,分享出来供大家参考学习,在开始之前,我们先来看一段代码: class Article(models.Model): title = models.... article = cached_fields.OneToOneField(Ar

    django model去掉unique_together报错的解决方案

    class Exam(models.Model): category = cached_fields.ForeignKeyField(Category) name = models.CharField(max_length=128) date = models.DateField() created_at = models.DateTimeField(auto_now_add=True) ...

    查看opensuse硬件信息

    Cached: 278952 kB SwapCached: 0 kB Active: 428520 kB Inactive: 221364 kB Active(anon): 349624 kB Inactive(anon): 464 kB Active(file): 78896 kB Inactive(file): 220900 kB Unevictable: 0 kB Mlocked: 0 kB...

    vmx-javascript-framework

    VMX Javascript 框架 这是 vmx javascript 框架的骨架。 所有与后端交互的 $vmx 方法都是异步的并使用一个 promise 框架(请参阅的 ...create(model_uuid) - 为给定的模型承诺一个新的连接 $vmx.detectorFactory g

    lm-explorer:语言模型的交互式资源管理器

    # This creates a local directory where the model can be cached so you don't # have to download it everytime you execute 'docker run'. $ mkdir -p / $HOME /.pytorch_pretrained_bert $ docker build -t lm-...

    Practical Mod Perl

    The Apache 1.3 Server Model Section 1.3. The Development of mod_perl 1.0 Section 1.4. Apache 1.3 Request Processing Phases Section 1.5. References Chapter 2. Getting Started ...

    php.ini-development

    ;;;;;;;;... 1.... 2.... 3.... 4.... 5.... 6.... The syntax of the file is extremely simple.... Section headers (e.g.... at runtime.... There is no name validation.... (e.g.... previously set variable or directive (e.g....

    ember-datalight:Ember 的轻量级数据持久化库,完全支持 JSON 结构

    Ember 数据灯Ember 的轻...特征结构化 JSON 使用标准 javascript 类型进行模型定义缓存(如果需要) CRUD 更好更小楷模您创建的每个模型都应该扩展 DataLight.Model 或 DataLight.CachedModel: var DL = require('emb

    Visual.Studio.Tools.for.Office.Using.C.Sharp.with.Excel.Word.Outlook.and.InfoPath.Sep.2005

    Advanced Topic: Deploying Network Solutions to Be Cached Locally Conclusion Part Four. Advanced Office Programming Chapter 21. Working with XML in Excel Introduction to Excel's XML...

    Visual.Studio.Tools.for.Office.Using.C.Sharp.with.Excel.Word.Outlook.and.InfoPath.Sep.2005.part2

    Advanced Topic: Deploying Network Solutions to Be Cached Locally Conclusion Part Four. Advanced Office Programming Chapter 21. Working with XML in Excel Introduction to Excel's XML...

    使用Delphi开发Client/Server应用程式

    歡迎來到Client/Server的世界 ...瞭解Transaction Model 正確的使用資料集元件(TTable,TQuery和TStoredProc) Cached Update和UpdateSQL的建立 企業物件(business object) 未來Client/Server架構的演變

    java-web-scaffold:基于SpringBoot的rest web基础脚手架,实现java工程快速开发

    Spring Cached with redis Mybatis代码生成 model标准化(AbstractEntity) jackJson序列化 Mockito 测试框架 Actuator 监控 统一Response格式 定时任务elastic job TODO rabbitMQ profile控制/Spring config 接入 ...

    普联架构设计技术方案.pptx

    Swing *Thin Client – GWT/HTML System Monitor Object Manager Dictionary Manager Fact Manager Model Manager Cached Manager Security Manager Offline Manager Convert Manager 安全服务 脚本服务 查询服务 ...

    Mastering.Spring.Cloud

    Implementing fallback with cached data The tripping circuit breaker Monitoring latency and fault tolerance Exposing Hystrix's metrics stream Hystrix dashboard Building an application with the ...

    Web Caching and Replication

    The ISO/OSI Reference Model Section 1.2. Network Components at Different Layers Section 1.3. Overview of Internet Protocols Section 1.4. Summary Chapter 2. The Internet Protocol and Routing...

    grasp:基本的NLP和ML,简短而快速的纯Python代码

    Grasp.py –可解释的AI ... src = dl ( 'https://www.textgain.com' , cached = True ) 将带有dom(html) HTML解析为一个Element树,并使用搜索: for e in dom ( src )( 'a[href^="http"]' ): # external links pr

    BURNINTEST--硬件检测工具

    PassMark BurnInTest V5.3 ...All Rights Reserved ... Overview ======== Passmark's BurnInTest is a software tool that allows all the major sub-systems of a computer to be simultaneously tested for reliability...

Global site tag (gtag.js) - Google Analytics