首页 > 数据库技术 > 详细

Mysql 优化

时间:2018-09-26 14:42:39      阅读:159      评论:0      收藏:0      [点我收藏+]

一: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>;

 

Mysql 优化

原文:https://www.cnblogs.com/blts/p/9706724.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!