ruby连接mysql,并在中间用memcached保存sql结果
好吧,我知道,这篇和前面一篇用python连接mysql的文章极大重复,我只是想试一下用ruby写程序,之前没玩过,很好奇。这里直接给最终结果了,步骤和python几乎完全一致。
先安装mysql的gem,还有依赖的其他lib
sudo apt-get install libmysqld-dev sudo apt-get install libmysqlclient-dev sudo gem install mysql
还需要安装ruby的memcached gem。
gem install memcache-client
然后是连接mysql和memcached的ruby代码
1 #!/usr/bin/env ruby 2 # 20140106, conn_mysql.rb 3 4 require "rubygems" 5 require "mysql" 6 require "memcache" 7 require "digest/md5" 8 9 class ConnMysql 10 def connect_db() 11 @client = Mysql.new("192.168.1.6", "dba", 12 "111111", "testdb") 13 end 14 15 def connect_cache() 16 server = ['localhost:11211'] 17 option = {} 18 @mc = MemCache.new(server, option) 19 end 20 21 def test_select() 22 result = @client.query("select * from id_info;") 23 24 result.each_hash do |row| 25 "id:#{row['id']}, info:#{row['info']}" 26 end 27 end 28 29 def test_count(str_sql) 30 result = @client.query(str_sql) 31 32 row = result.fetch_row() 33 return "#{row[0]}" 34 end 35 36 def test_count_cached(str_sql) 37 str_hash = Digest::MD5.hexdigest(str_sql) 38 39 result = @mc[str_hash] 40 if result != nil 41 return result 42 end 43 puts Digest::MD5.hexdigest(str_sql) 44 result = @client.query(str_sql) 45 46 row = result.fetch_row() 47 @mc[str_hash] = row 48 49 str_rows = "#{row[0]}" 50 return str_rows 51 end 52 53 def disconnect_db() 54 @client.close() 55 end 56 57 end
然后是不使用memcached,直接去mysql查询的代码
1 #!/usr/bin/env ruby 2 # 20140106, conn_mysql_raw.rb 3 4 require "rubygems" 5 6 require_relative "conn_mysql" 7 8 str_sql = "select count(*) from id_info where info like \'bbb%\';" 9 10 db_connect = ConnMysql.new 11 db_connect.connect_db() 12 result = "" 13 i = 0 14 15 while i < 10000 16 result = db_connect.test_count(str_sql) 17 i += 1 18 end 19 20 puts "#{result} rows selected." 21 22 db_connect.disconnect_db()
最后是使用memcached的代码,当然运行的时候,需要memcached服务是运行着的
1 #!/usr/bin/env ruby 2 # 20140106, conn_mysql_memcached.rb 3 4 require "rubygems" 5 6 require_relative "conn_mysql" 7 8 str_sql = "select count(*) from id_info where info like \'bbb%\';" 9 10 db_connect = ConnMysql.new 11 db_connect.connect_db() 12 db_connect.connect_cache() 13 14 result = "" 15 i = 0 16 17 while i < 10000 18 result = db_connect.test_count_cached(str_sql) 19 i += 1 20 end 21 22 puts "#{result} rows selected." 23 24 db_connect.disconnect_db()
两者相比,时间上分别是2.9s和1.5s,似乎整体上比python慢一点,不知道问题在哪。