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

Cache SHOW COLUMNS

阅读更多
今天recity发布第二版本,优化了半天,终于达到一个稍微满意的速度,闲下来也写了篇bllog轻松下:)


这个东西据说在production已经cache了,是的,确实是的!

今天主要的目的是折腾 于是乎google一把,看有没有现成的plugin,呵呵,俺想偷懒

没找到plugins,但是找到一个不错的patch:http://dev.rubyonrails.org/attachment/ticket/9046/cache_column_names.patch

哦,原来就是这么个东西,开始动手,把它转换成plugins

先说明下,这个只是初步入门级别,没什么深入研究的可是为什么要写这篇文章:
呵呵,纯属折腾。。。

新建一个plugin
ruby script/generate plugin CacheColumns


将cache_column_name.patch的代码稍作修改填到我们的lib/cache_columns里去
这里面的columns和reset_column_information是实类方法,所以我们可以使用
base.instance_eval do
  block goes here
end

来覆盖原始的method

首先请先备份原始的两个method
        alias old_columns columns
        alias old_reset_column_information reset_column_information


新建一个全局的变量Hash来缓存columns
@@columns = {}


OK,include 到ActiveRecord::Base里去
ActiveRecord::Base.send :include, CacheColumns::ActiveRecord

打完收工

完整代码如下:
/vendor/plugins/cache_columns/init.rb
ActiveRecord::Base.send :include, CacheColumns::ActiveRecord



/vendor/plugins/cache_columns/lib/cache_columns.rb
module CacheColumns
  module ActiveRecord
    @@columns = {}

    def self.included(base)
      base.instance_eval do
        alias old_columns columns
        alias old_reset_column_information reset_column_information

        def columns
          if  @@columns[table_name].nil?
            @@columns[table_name] = connection.columns(table_name, "#{name} Columns")
            @@columns[table_name].each {|column| column.primary = column.name == primary_key}
          end
          @@columns[table_name]
        end

        #  # Resets all the cached information about columns, which will cause them to be reloaded on the next request.
        def reset_column_information
          generated_methods.each { |name| undef_method(name) }
          @column_names = @columns_hash = @content_columns = @dynamic_methods_hash = @read_methods = @inheritance_column = nil
          @@columns.delete(table_name)
        end

        def reset_column_cache #:nodoc:
          @@columns = {}
        end
      end
    end
end



代码我放到code.google.com上面去了
svn co http://cache-columns.googlecode.com/svn/trunk


哦,你想缓存到memcached中?好吧,我们再继续修改之,有过一次经历,这次再动手就简单多了。
require 'memcache_util'

module CacheColumns
  module ActiveRecord
    def self.included(base)
      base.instance_eval do
        alias old_columns columns
        alias old_reset_column_information reset_column_information
        @ttl = 60 * 30 #增加个配置选择?

        def columns
          record =  get_columns(table_name)
          unless record
            record = connection.columns(table_name, "#{name} Columns")
            record.each {|column| column.primary = column.name == primary_key}
            cache_store record
          end
          record
        end

        #  # Resets all the cached information about columns, which will cause them to be reloaded on the next request.
        def reset_column_information
          generated_methods.each { |name| undef_method(name) }
          @column_names = @columns_hash = @content_columns = @dynamic_methods_hash = @read_methods = @inheritance_column = nil
          cache_delete
        end

        #get columns from memcached
        def get_columns(name)
          start_time = Time.now
          record = Cache.get cache_key_memcache
          elapsed = Time.now - start_time
          ActiveRecord::Base.logger.debug('CacheColumns Get (%0.6f)  %s' % [elapsed, cache_key_memcache])
          record
        end

        #store columns
        def cache_store(record)
          start_time = Time.now
          Cache.put cache_key_memcache, record, @ttl
          elapsed = Time.now - start_time
          ActiveRecord::Base.logger.debug('CacheColumns Set (%0.6f)  %s' % [elapsed, cache_key_memcache])
          record
        end

        def cache_key_memcache
          "active_record:columns:#{table_name}"
        end

        def cache_delete
          Cache.delete  cache_key_memcache
        end
      end
    end
  end
end



分享到:
评论
5 楼 xxj 2008-01-14  
http://rails-analyzer.rubyforge.org/pl_analyze/
+
http://nubyonrails.com/articles/a-hodel-3000-compliant-logger-for-the-rest-of-us

其实这个东西我基本不用,偶尔需要查看看Controller的效率,才会把日志分析看看。
4 楼 lgn21st 2008-01-14  
hodel_3000_compliant_logger
pl_analyzer
这两个东西都没有接触过,正在google中
能介绍一下么?
3 楼 xxj 2008-01-14  
不是的,我用了hodel_3000_compliant_logger,便于用pl_analyzer分析日志用。

require 'logger'
require 'English'
# Jan  2 03:38:05 topfunky postfix/postqueue[2947]: warning blah blah blah

##
# A logger for use with pl_analyze and other tools that expect syslog-style log output.

class Hodel3000CompliantLogger < Logger
  
  ##
  # Note: If you are using FastCGI you may need to hard-code the hostname here instead of using Socket.gethostname
  
  def format_message(severity, timestamp, msg, progname) 
    "#{timestamp.strftime("%b %d %H:%M:%S")} #{Socket.gethostname.split('.').first} rails[#{$PID}]: #{progname.gsub(/\n/, '').lstrip}\n"
  end
end


所以能看到的.
2 楼 lgn21st 2008-01-11  
在production环境下,SQL语句默认不会output吧,莫非被人为打开了?
1 楼 Readonly 2008-01-11  
引用
这个东西据说在production已经cache了,但是我从log分析来看

难道你在production log下有发现SHOW COLUMNS的语句不断被打出?

相关推荐

    上网监控工具

    - DNS Cache for fast hostname resolution - Log XNS activity to file / Log Manager - Feature-Centric customizable toolbar - ViewBar & System Tray Access - Remote Access thru X-NetStat Web Server - ...

    bootstrap table操作技巧分享

    本文实例为大家分享了bootstrap table操作的相关... data-height="800" data-show-columns="true" data-smart-display = "true" data-async = false data-query-params="bh_agt_queryParams" data-search="true" d

    android lint performance probe帮助.zip

    This is a simple tool to help pinpoint performance bottlenecks in individual ...For example, the first Lint check to run might get the blame for the initial cache misses when resolving calls, types, etc.

    php.ini-development

    user_ini.cache_ttl = 300 ;;;;;;;;;;;;;;;;;;;; ; Language Options ; ;;;;;;;;;;;;;;;;;;;; ; Enable the PHP scripting language engine under Apache. ; http://php.net/engine engine = On ; This directive...

    Oracle事例

    SQL&gt;select table_name,cache from user_tables where instr(cache,\'Y\')&gt;0; 28、约束条件 create table employee (empno number(10) primary key, name varchar2(40) not null, deptno number(2) default ...

    sqlmap (懂的入)

    enumerate users, users password hashes, databases, tables, columns, dump tables entries, dump the entire DBMS, retrieve an arbitrary file content (if the remote DBMS is MySQL) and provide your own ...

    FastReport.v4.15 for.Delphi.BCB.Full.Source企业版含ClientServer中文修正版支持D4-XE5

    - fixed bug in ODF export with properties table:number-columns-spanned, table:number-rows-spanned - fixed bug in ODF export with the background clNone color - fixed bug in ODF export with a style of ...

    linux.chm文档

    ls /tmp | pr -T5 -W$COLUMNS 将终端划分成5栏显示 chmod ugo+rwx directory1 设置目录的所有人(u)、群组(g)以及其他人(o)以读(r )、写(w)和执行(x)的权限 chmod go-rwx directory1 删除群组(g)与其他人(o)对...

    EurekaLog_7.5.0.0_Enterprise

    13)..Added: "User" and "Session" columns to processes list, processes list is also sorted by session first 14)..Added: Support for showing current user processes only 15)..Added: Expanding environment...

    js使用小技巧

    Javascript小技巧一箩筐 事件源对象 event.srcElement.tagName event.srcElement.type ... 捕获释放 event.srcElement.setCapture();...event.srcElement.releaseCapture();... 根据鼠标获得元素: document....

    曲线拟合工具CurveExpert 1.0

    from the cache instead of recalculating the curve fit. Fixed. + running two versions of CurveExpert is prevented, since two simultaneous instances cause stack faults. + if the data set is sorted,...

    WordPress 2.7 Cookbook.pdf

    Optimizing your blog performances with WP Super Cache 86 Getting ready 86 How to do it 86 How it works 87 There's more... 87 Prevent URLs from being cached 87 Adding redirects for changed ...

    微软内部资料-SQL性能优化3

    Contents Overview 1 Lesson 1: Concepts – Locks and Lock Manager 3 Lesson 2: Concepts – Batch and Transaction 31 Lesson 3: Concepts – Locks and Applications 51 Lesson 4: Information Collection and ...

Global site tag (gtag.js) - Google Analytics