zoukankan      html  css  js  c++  java
  • Mysql 优化

    一:Mysql 大批量数据插入

    -- test1.sql
    TRUNCATE TABLE t_integer;
    INSERT t_integer (test_id, test_value)
    VALUES (1, 1234),
    (2, 1234),
    (3, 1234),
    (4, 1234),
    (5, 1234),
    (6, 1234),
    ... ...
    (9997, 1234),
    (9998, 1234),
    (9999, 1234),
    (10000, 1234);
    -- test2.sql
    TRUNCATE TABLE t_integer;
    INSERT t_integer (test_id, test_value) VALUES (1, 1234);
    INSERT t_integer (test_id, test_value) VALUES (2, 1234);
    INSERT t_integer (test_id, test_value) VALUES (3, 1234);
    INSERT t_integer (test_id, test_value) VALUES (4, 1234);
    INSERT t_integer (test_id, test_value) VALUES (5, 1234);
    INSERT t_integer (test_id, test_value) VALUES (6, 1234);
    ... ...
    INSERT t_integer (test_id, test_value) VALUES (9997, 1234);
    INSERT t_integer (test_id, test_value) VALUES (9998, 1234);
    INSERT t_integer (test_id, test_value) VALUES (9999, 1234);
    INSERT t_integer (test_id, test_value) VALUES (10000, 1234);

    以上两个脚本通过mysql命令行运行,分别耗时0.44秒和136.14秒,相差达300倍。

    基于这个思路,只要将需插入的数据进行合并处理,只需要一条SQL语句 就可以轻松达到每秒1000条的设计要求了。

    二:Mysql 常用数据查询

    这里需要使用到memcache缓存,第一次从数据表读取,读完以后,存入到memcache的内存中,给她设定一个周期为一分钟的$key,

    当再次访问这个接口的时候 ,就获取memcache 中的 $key 是否存在 $memcache->get($key),存在就读取缓存,否则就需要去数据库查询内容

    //建立sql语句
    $sql = 'select * from ml_type';
    $key = md5($sql);
    
    if ($memcache->get($key)) {
        //memecache缓存区间
        echo '我是读的memcache缓存';
        $result = $memcache->get($key);
    } else {
        //mysql区间
        echo '我是读的mysql';
        $handle = mysql_query($sql);
        if ($handle) {
            $result = array();
            while ($array = mysql_fetch_array($handle)) {
                $result[] = array(
                    'id' => $array['id'],
                    'name' => $array['name']
                );
            }
        }
        mysql_close();                                          //关闭mysql资源
        $memcache->set($key, $result, MEMCACHE_COMPRESSED, 5);  //MEMCACHE_COMPRESSED是常量1. 缓存20秒
    }
    
    
    echo '<pre>';
    print_r($result);
    echo '</pre>';
  • 相关阅读:
    归并排序(Merge Sort)
    AtCoder AGC035D Add and Remove (状压DP)
    AtCoder AGC034D Manhattan Max Matching (费用流)
    AtCoder AGC033F Adding Edges (图论)
    AtCoder AGC031F Walk on Graph (图论、数论)
    AtCoder AGC031E Snuke the Phantom Thief (费用流)
    AtCoder AGC029F Construction of a Tree (二分图匹配)
    AtCoder AGC029E Wandering TKHS
    AtCoder AGC039F Min Product Sum (容斥原理、组合计数、DP)
    AtCoder AGC035E Develop (DP、图论、计数)
  • 原文地址:https://www.cnblogs.com/blts/p/9706724.html
Copyright © 2011-2022 走看看