待学习
月度归档: 2017年5月
MySQL体系结构
thread pool是在连接层处理
这里的授权是这个用户对某个表某个列是否有权限
查询缓存是全局锁 不建议使用查询缓存
关闭查询缓存:
query_cache_type=0
query_cache_size=0
2个参数都要设置
mysql proxy 是在最开始的连接层
handlersocket,可以绕过连接层,sql层,直接操作Innodb存储引擎所以效率非常高,后来基本上都不使用了,NOSQL流行起来了
经典的mysql体系结构图
-
最前端的是各种语言与mysql相互连接的API或者是接口协议
-
连接的pool,mysql不支持 只是用这个来表示 可以用自己开的proxy 或者是官方的proxy实现
-
SQL Interface :接收用户所有的sql指令
-
解析器(Parser):把sql命令解析 (YACC这个语法解析器来解析sql语法)
-
将SQL语句分解成数据结构,并将这个结构传递到后续步骤,以后SQL语句的传递和处理就是基于这个结构的。
-
如果在分解构成中遇到错误,那么就说明这个sql语句是不合理的。
-
Optimizer查询优化器
-
查询缓存
-
query_cache, key_bufer, innodb_buffer
-
再下面一层是存储引擎层-插拔式
Cache&Buffer的组成
上面的框:tmp_table_size & max_heap_table_size 线程创建分配 这个是会话级的内存结构
下面的框:全局内存,程序启动就分配,只分配一次,全局公用
PGA如果分配过高,可能会导致OOM(内存溢出)
mysql使用总内存=global buffers + thread_buffers
MySQL innodb引擎和myisam的引擎执行对比测试
http://www.itpub.net/thread-1902289-1-1.html
MySQL 利用硬件资源特点
CPU的利用特点
-
<5.1 多核心支持较弱
-
5.1 可以利用4个核
-
5.5 可以利用24个核
-
5.6 可以利用64个核
-
每个连接对应一个线程,每个并发query只能使用到一个核
内存利用特点:
-
类似ORACLE的SGA,PGA模式,注意PGA不宜分配过大
-
内存管理简单,有效。在高TPS,高并发环境下,可增加物理内存以减少物理IO,提高并发性能
-
官方分支锁并发竞争比较严重,MariaDB,Percona进行优化
-
有类似ORACLE library cache的query cache,但效过不佳,建议关闭
-
执行计划没有缓存(类似ORACLE library cache)
-
通常内存建议按热点数据总量的15%-20%来规划,专用单实例则可以分配物理内存的50%~70%左右
-
类似K-V简单数据,采用memcached,Redis等NOSQL来缓存
磁盘
-
undo log的I/O特征:顺序写,随机读
-
Redo log,Binlog的I/O特性:顺序写,顺序读
-
数据文件的I/O特性:随机写,随机读
-
OLTP业务以随机IO为主,建议加到内存,尽量合并随机IO为顺序IO
-
OLAP业务以顺序IO为主,极大内存的同时增加硬盘数量提高顺序IO性能
-
MyISAM是堆组织表(HOT),InnoDB是索引组织表(IOT)
-
InnoDB相比MyISAM更消耗磁盘空间
show engine innodb status
记录一下 给自己设置个锚点 以后补充内容
Mysql metadata lock(MDL)
metadata lock5.5.3 引入
当事务访问处理过程中执行DDL操作将会等到metadata lock执行完毕才能操作
如果没有访问这个表 是可以被ddl操作的
没数据的情况下可以ddl操作
在事务里不要用DDL 有隐式提交
坑:会话2执行drop 操作 wait 再开会话3执行select也是操作不了的 要等会话2的drop执行完了才能查询
所以很容易把线上库卡住
解决办法:kill掉 drop
线上DB不要轻易做alter table
在生产中做DDL操作时请冷静思考一下
演示:
begin这里只是为了模拟事务
如果事务中一个sql跑的很慢也会出现这种情况
我开启了2个会话
在会话1里申明一个显示的事务
在会话2里drop leo_copy表
就会看到这个时候drop不掉le_copy表
state是“Waiting for table metadata lock”
FLUSH TABLES WITH READ LOCK 和 LOCK TABLES比较
1、FLUSH TABLES WITH READ LOCK
这个命令是全局读锁定,执行了命令之后所有库所有表都被锁定只读。一般都是用在数据库联机备份,这个时候数据库的写操作将被阻塞,读操作顺利进行。解锁的语句也是unlock tables。
2、LOCK TABLES tbl_name [AS alias] {READ [LOCAL] | [LOW_PRIORITY] WRITE}
这个命令是表级别的锁定,可以定制锁定某一个表。例如: lock tables test read; 不影响其他表的写操作。解锁语句也是unlock tables。
这两个语句在执行的时候都需要注意个特点,就是 隐式提交的语句。在退出mysql终端的时候都会隐式的执行unlock tables。也就是如果要让表锁定生效就必须一直保持对话。
3、MYSQL的read lock和wirte lock
read-lock: 允许其他并发的读请求,但阻塞写请求,即可以同时读,但不允许任何写。也叫共享锁
write-lock: 不允许其他并发的读和写请求,是排他的(exclusive)。也叫独占锁
python3 pandas基本操作
1 2 3 4 5 6 7 8 | #encodeing=utf-8 import numpy as np import pandas as pd s = pd.Series([i * 2 for i in range ( 1 , 11 )]) dates = pd.date_range( "20170301" , periods = 8 ) df = pd.DataFrame(np.random.randn( 8 , 5 ),index = dates,columns = list ( "ABCDE" )) print (df) |
随机生成8行5列 以dates作为index,ABCDE作为列
1 2 3 4 5 | #打印前3行 print (df.head( 3 )) #打印后三行 print (df.tail( 3 )) |
1 2 3 4 5 | #打印索引值 print (df.index) #打印value print (df.values) |
1 2 | #转制 索引和列转换 print (df.T) |
1 | print (df.sort(columns = "C" )) |
我测试sort的时候尽然报错 可能是python3对排序重新定义了函数名
1 | print (df.sort_index(axis = 1 ,ascending = False )) |
1 | print (df.describe()) |
1 2 3 | #切片 print (df[ "A" ]) print ( type (df[ "A" ])) |
1 2 3 4 5 | print (df[: 3 ]) print ( "=============================================================" ) print (df[ "20170301" : "20170304" ]) print ( "=============================================================" ) print (df.loc[dates[ 0 ]]) |
1 2 3 | print (df.loc[ "20170301" : "20170304" ,[ "B" , "D" ]]) print ( "=============================================================" ) print (df.at[dates[ 0 ], "C" ]) |
1 2 | #通过下标进行选择 print (df.iloc[ 1 : 3 , 2 : 4 ]) |
1 2 3 4 5 6 | #填条件进行筛选 print (df[df.B> 0 ][df.A< 0 ]) print ( "=============================================================" ) print (df[df> 0 ]) print ( "=============================================================" ) print (df[df[ "E" ].isin([ 1 , 2 ])]) |
1 2 3 4 5 6 7 8 9 | df.iat[ 1 , 1 ] = 1 print (df) df.loc[:, "D" ] = np.array([ 4 ] * len (df)) print (df) df2 = df.copy() df2[df2> 0 ] = - df2 print (df2) |
1 2 3 4 5 6 7 8 9 | df1 = df.reindex(index = dates[: 4 ],columns = list ( "ABCD" ) + [ "G" ]) df1.loc[dates[ 0 ]:dates[ 1 ], "G" ] = 1 # print(df1) #丢弃NaN的行 print (df1.dropna()) #填充NaN print (df1.fillna(value = 2 )) |
http://www.imooc.com/video/14994
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | #encodeing=utf-8 import sys import os import re import numpy as np import pandas as pd from pandas import Series, DataFrame, Panel logfile = 'www.xxxxxx.com-access_log-20170521' with open (logfile, 'r' ) as fo: log_list = [] for line in fo: regex = '([(\d\.)]+) - - \[(.*?)\] "(.*?)" (\d+) (\d+|-)' rline = re.match(regex, line).groups() log_list.append(rline) indexs = [ 'IP' , 'Time' , 'Result' , 'Status' , 'No.' ] df = DataFrame(log_list,columns = indexs) print (df) # print(df[df['IP'] == '42.120.160.97']) |
像sql一样使用pandas 可以参考下面这篇文章
http://www.cnblogs.com/en-heng/p/5630849.html
python3 模拟登陆
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | import urllib.request, urllib.parse, urllib.error import http.cookiejar login_url = 'http://blog.leokim.cn/wp-login.php' values = { 'log' : 'xxxxxxx' , 'pwd' : 'xxxxxxxxxxxxx' } postdata = urllib.parse.urlencode(values).encode() user_agent = r 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36' headers = { 'User-Agent' : user_agent, 'Connection' : 'keep-alive' } cookie_filename = 'cookie.txt' cookie = http.cookiejar.MozillaCookieJar(cookie_filename) handler = urllib.request.HTTPCookieProcessor(cookie) opener = urllib.request.build_opener(handler) request = urllib.request.Request(login_url, postdata, headers) try : response = opener. open (request) page = response.read().decode() # print(page) except urllib.error.URLError as e: print (e.code, ':' , e.reason) cookie.save(ignore_discard = True , ignore_expires = True ) # 保存cookie到cookie.txt中 print (cookie) for item in cookie: print ( 'Name = ' + item.name) print ( 'Value = ' + item.value) get_url = 'http://blog.leokim.cn/wp-admin/edit.php' # 利用cookie请求访问另一个网址 get_request = urllib.request.Request(get_url, headers = headers) get_response = opener. open (get_request) print (get_response.read().decode()) |
用cookie直接访问
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | import urllib.request, urllib.parse, urllib.error import http.cookiejar cookie_filename = 'cookie.txt' cookie = http.cookiejar.MozillaCookieJar(cookie_filename) cookie.load(cookie_filename, ignore_discard = True , ignore_expires = True ) handler = urllib.request.HTTPCookieProcessor(cookie) opener = urllib.request.build_opener(handler) get_url = 'http://blog.leokim.cn/wp-admin/tools.php' get_request = urllib.request.Request(get_url) get_response = opener. open (get_request) print (get_response.read().decode()) |
python3 创建Opener对象以实现Cookie与其它HTTP功能
基本的urlopen()函数不支持验证、cookie或其他HTTP高级功能。
要支持这些功能,必须使用build_opener()函数来创建自己的自定义Opener对象。
install_opener(opener) 安装opener作为urlopen()使用的全局URL opener,即意味着以后调用urlopen()时都会使用安装的opener对象。opener通常是build_opener()创建的opener对象。
一些复杂情况详细解决办法:
1. cookie处理
如果要管理HTTP cookie,需要创建添加了HTTPCookieProcessor处理程序的opener对象。默认情况下。HTTPCookieProcessor使用CookieJar对象,将不同类型的CookieJar对象作为HTTPCookieProcessor的参数提供,可支持不同的cookie处理。如下面代码:
url = 'http://www.baidu.com' postdata = '' cookie_filename = 'cookie.txt' cookie =http.cookiejar.MozillaCookieJar(cookie_filename) handler = urllib.request.HTTPCookieProcessor(cookie) opener = urllib.request.build_opener(handler) request = urllib.request.Request(url, postdata, headers)
2.proxy代理
1 2 3 4 5 6 7 | import urllib.request proxy_handler = urllib.request.ProxyHandler({ 'http' : '123.123.2123.123:8080' }) proxy_auth_handler = urllib.request.ProxyBasicAuthHandler() proxy_auth_handler.add_password( 'realm' , '123.123.2123.123' , 'user' , 'password' ) opener = urllib.request.build_opener(urllib.request.HTTPHandler, proxy_handler) f = opener. open ( 'http://www.baidu.com' ) a = f.read() |
Python3 urllib使用方法
我自己码了一遍结果没注意浏览器返回上一页了 艹
直接复制粘贴了吧 再搞一遍太麻烦了
1、最简单
1 2 3 | import urllib.request response = urllib.request.urlopen( 'http://python.org/' ) html = response.read() |
2、使用 Request
1 2 3 4 | import urllib.request req = urllib.request.Request( 'http://python.org/' ) response = urllib.request.urlopen(req) the_page = response.read() |
3、发送数据
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | #! /usr/bin/env python3 import urllib.parse import urllib.request url = 'http://localhost/login.php' user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' values = { 'act' : 'login' , 'login[email]' : 'yzhang@i9i8.com' , 'login[password]' : '123456' } data = urllib.parse.urlencode(values) req = urllib.request.Request(url, data) req.add_header( 'Referer' , 'http://www.python.org/' ) response = urllib.request.urlopen(req) the_page = response.read() print (the_page.decode( "utf8" )) |
4、发送数据和header
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | #! /usr/bin/env python3 import urllib.parse import urllib.request url = 'http://localhost/login.php' user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' values = { 'act' : 'login' , 'login[email]' : 'yzhang@i9i8.com' , 'login[password]' : '123456' } headers = { 'User-Agent' : user_agent } data = urllib.parse.urlencode(values) req = urllib.request.Request(url, data, headers) response = urllib.request.urlopen(req) the_page = response.read() print (the_page.decode( "utf8" )) |
5、http 错误
1 2 3 4 5 6 7 8 | #! /usr/bin/env python3 import urllib.request req = urllib.request.Request( 'http://www.111cn.net ' ) try : urllib.request.urlopen(req) except urllib.error.HTTPError as e: print (e.code) print (e.read().decode( "utf8" )) |
6、异常处理1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | #! /usr/bin/env python3 from urllib.request import Request, urlopen from urllib.error import URLError, HTTPError req = Request( "http://www.111cn.net /" ) try : response = urlopen(req) except HTTPError as e: print ( 'The server couldn' t fulfill the request.') print ( 'Error code: ' , e.code) except URLError as e: print ( 'We failed to reach a server.' ) print ( 'Reason: ' , e.reason) else : print ( "good!" ) print (response.read().decode( "utf8" )) |
7、异常处理2
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | #! /usr/bin/env python3 from urllib.request import Request, urlopen from urllib.error import URLError req = Request( "http://www.111cn.net /" ) try : response = urlopen(req) except URLError as e: if hasattr (e, 'reason' ): print ( 'We failed to reach a server.' ) print ( 'Reason: ' , e.reason) elif hasattr (e, 'code' ): print ( 'The server couldn' t fulfill the request.') print ( 'Error code: ' , e.code) else : print ( "good!" ) print (response.read().decode( "utf8" )) |
8、HTTP 认证
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | #! /usr/bin/env python3 import urllib.request # create a password manager password_mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm() # Add the username and password. # If we knew the realm, we could use it instead of None. top_level_url = "https://www.111cn.net /" password_mgr.add_password( None , top_level_url, 'rekfan' , 'xxxxxx' ) handler = urllib.request.HTTPBasicAuthHandler(password_mgr) # create "opener" (OpenerDirector instance) opener = urllib.request.build_opener(handler) # use the opener to fetch a URL a_url = "https://www.111cn.net /" x = opener. open (a_url) print (x.read()) # Install the opener. # Now all calls to urllib.request.urlopen use our opener. urllib.request.install_opener(opener) a = urllib.request.urlopen(a_url).read().decode( 'utf8' ) print (a) |
9、使用代理
1 2 3 4 5 6 7 | #! /usr/bin/env python3 import urllib.request proxy_support = urllib.request.ProxyHandler({ 'sock5' : 'localhost:1080' }) opener = urllib.request.build_opener(proxy_support) urllib.request.install_opener(opener) a = urllib.request.urlopen( "http://www.111cn.net " ).read().decode( "utf8" ) print (a) |
10、超时
1 2 3 4 5 6 7 8 9 10 11 | #! /usr/bin/env python3 import socket import urllib.request # timeout in seconds timeout = 2 socket.setdefaulttimeout(timeout) # this call to urllib.request.urlopen now uses the default timeout # we have set in the socket module req = urllib.request.Request( 'http://www.111cn.net /' ) a = urllib.request.urlopen(req).read() print (a) |