字典
字典dictionary
字典是另外一种可变容器类型,且可以存储任意类型对象。列表元素进行修改的话,通过索引进行修改,如果当前元素的顺序发生改变,此时还需要修改索引才能完成修改。然而字典既能存储多个数据,又能方便准确的定位元素。
创建字典
语法:
字典名 = {key1:value1,key2:value2,...}
示例:
student = {'name':'tom','age':18,'sex':'男'}
访问字典
students = {'name':'张三','age':18,'address':'北京'}
print(students['name']) #根据key找到值
返回结果:
张三
修改字典
通过找到指定的key进行修改
students = {'name':'张三','age':18,'address':'北京'}
students['name'] = '李四'
print(students)
返回结果:
{'name': '李四', 'age': 18, 'address': '北京'}
添加字典元素
students = {'name':'张三','age':18,'address':'北京'}
students['hobby'] = '足球'
print(students)
返回结果:
{'name': '张三', 'age': 18, 'address': '北京', 'hobby': '足球'}
删除字典
del 字典名[key]
:指定key删除
students = {'name':'张三','age':18,'address':'北京'}
del students['address'] #指定key删除元素
print(students)
返回结果:
{'name': '张三', 'age': 18}
del 字典名
:删除字典
students = {'name':'张三','age':18,'address':'北京'}
del students #删除字典,删除后结果为NameError: name 'students' is not defined,未定义
print(students)
返回结果:
NameError: name 'students' is not defined
字典名.clear()
:清空整个字典元素,保留一个空的字典
students = {'name':'张三','age':18,'address':'北京'}
students.clear()
print(students)
返回结果:
{}
字典函数
len(dict)
:计算字典中元素的个数
dict1 = {'name':'tom','age':18,'sex':'男','hobby':'足球'}
print(len(dict1))
返回结果:
4
str(dict)
:输出字典,也可打印的字符串表示
dict1 = {'name':'tom','age':18,'sex':'男','hobby':'足球'}
str1 = str(dict1)
print(str1)
print(type(str1)) #判断str1的数据类型
返回结果:
{'name': 'tom', 'age': 18, 'sex': '男', 'hobby': '足球'}
<class 'str'>
type(variable)
:返回输入变量的数据类型,如果变量是字典就返回<class 'dict'>
dict1 = {'name':'tom','age':18,'sex':'男','hobby':'足球'}
print(type(dict1))
返回结果:
<class 'dict'>
dict.fromkeys(seq[,value])
:创建一个新字典,以序列seq元素做字典的值,value为字典所有键对应的初始值
seq = ('name','age','sex')
dict1 = dict.fromkeys(seq)
print("新字典为:",dict1)
dict2 = dict.fromkeys(seq,'jack')
print("新字典为:",dict2)
返回结果:
新字典为: {'name': None, 'age': None, 'sex': None}
新字典为: {'name': 'jack', 'age': 'jack', 'sex': 'jack'}
dict.get(key,default=None)
:返回指定键的值,如果值不在字典中返回default值,如果字典存在该key对应的元素,就输出原值,否则输出该key输入值
dict1 = {'name':'tom','age':18}
print("age键的值为:",dict1.get('age',9))
print("sex键的值为:",dict1.get('sex','男'))
返回结果:
age键的值为: 18
sex键的值为: 男
key in dict
:如果key在字典dict中则返回True,否则返回False
dict1 = {'name':['tom','jack'],'age':19,'sex':'男','hobby':'足球'}
if 'name' in dict1:
print("键name在字典中存在")
else:
print("键name在字典中不存在")
返回结果:
键name在字典中存在
dict.keys()
:以列表返回一个字典所有键名
dict1 = {'name':['tom','jack'],'age':19,'sex':'男','hobby':'足球'}
print(dict1.keys())
返回结果:
dict_keys(['name', 'age', 'sex', 'hobby'])
dict.setdefault(key,default=None)
:和get类似,但如果键不存在字典中,将会添加键并将值设为default
dict1 = {'name':'tom','age':19}
print("age键的值为:",dict1.setdefault('age',9))
print("sex键的值为:",dict1.setdefault('sex','男'))
print("新字典为:",dict1)
返回结果:
age键的值为: 19
sex键的值为: 男
新字典为: {'name': 'tom', 'age': 19, 'sex': '男'}
dict.values()
:以列表返回一个字典中的所有值
dict1 = {'name':'tom','age':19}
print(dict1.values())
print(dict1.items()) #将键值对返回并且返回至元组中
返回结果:
dict_values(['tom', 19])
dict_items([('name', 'tom'), ('age', 19)])
元组
元组tuple
元组和列表类似,不通过之处在于元组的元素不能被修改,而列表元素是可以被修改的,也可以进行分片和连接操作。元组使用小括号()创建,列表使用中括号[]创建。
元组的创建语法
元组名 = (元素1,元素2,元素3,...)
示例
student = ('jack','tom','jone')
删除元组
语法:del 元组名
示例:
tuple1 = ('abc',123,'hello')
print("删除之前的元组为:",tuple1)
del tuple1
print("删除后的元组为:",puple1) #因为del删除是在内存中彻底将元组删除,即删除后结果为名称未定义,找不到元组名
返回结果:
删除之前的元组为: ('abc', 123, 'hello')
print("删除后的元组为:",puple1)
NameError: name 'puple1' is not defined
元组切片截取
元组的元素虽然不能够被改变,但是元组也是一个序列,也可以通过索引去访问和截取元组中指定位置的元素
tup01 = ('tom','jack','aimi','lili','black')
print(tup01[0:3])
返回结果:
('tom', 'jack', 'aimi')
多维元组
多维元组就是在元祖中包含元组,元祖中的元素可以是一个新的元组
tup01 = ('tom','jack',['aimi','lili'],'black')
print(tup01[2][1])
返回结果:
lili
元组函数
len(tuple)
:计算元组中素的个数
tup01 = ('tom','jack','aimi','lili','black')
print(len(tup01)) #统计元组中元素的个数
返回结果:
5
max(tuple)
:返回元组中元素的最大值
tup01 = (2,6,5,8,9)
print(max(tup01))
返回结果:
9
min(tuple)
:返回元祖中元素的最小值
tup01 = (2,6,5,8,9)
print(min(tup01))
返回结果:
2
tuple(list)
:将列表转换为元组
students = ['jack','tom','john','amy','kim','sunny']
print('转换前:',students)
print('转换后:',tuple(students))
print('再次转换后:',list(students))
返回结果:
转换前: ['jack', 'tom', 'john', 'amy', 'kim', 'sunny']
转换后: ('jack', 'tom', 'john', 'amy', 'kim', 'sunny')
再次转换后: ['jack', 'tom', 'john', 'amy', 'kim', 'sunny']
列表
列表list
列表是由一系列按特定顺序排列的元素组成,列表能存储多种数据类型,其中的元素之间可以没有任何关系。
访问列表元素
list01 = ['jack','jane','black']
print(list01[2]) #通过下标获取black
返回结果:
black
修改列表元素
修改列表元素的语法和访问列表元素的语法类似,指定列表名和要修改的索引,在指定新值
list01 = ['jack','jane',['dahei','joe'],'black']
list01[0] = 'lili' #通过下标获取列表元素,并赋予新值
print(list01)
list01[2][0] = 'susan' #通过下标获取列表元素,并赋予新值
print(list01)
#列表是一个可变的类型数据,允许我们对立面的元素进行修改
返回结果:
['lili', 'jane', ['dahei', 'joe'], 'black']
['lili', 'jane', ['susan', 'joe'], 'black']
添加元素
append
:列表末尾添加元素
list02 = ['jack','jane',['dahei','joe'],'black']
list02.append('susan') #在列表末尾添加元素susan
print(list02)
返回结果:
['jack', 'jane', ['dahei', 'joe'], 'black', 'susan']
insert
:列表指定下标位置添加元素
list02 = ['jack','jane',['dahei','joe'],'black']
print(list02) #修改前
print('_'*40)
list02.insert(3,'susan')
print(list02) #修改后
返回结果:
['jack', 'jane', ['dahei', 'joe'], 'black']
________________________________________
['jack', 'jane', ['dahei', 'joe'], 'susan', 'black']
删除元素
pop()
:默认删除最后一个,可以指定位置删除,并且删除时返回删除内容
list03 = ['jack','jane','joe','black']
print('删除前的元素为:',list03)
print('_'*40)
print('默认删除的元素为:',list03.pop()) #默认删除操作,并且返回删除的元素
print('删除后的剩余元素为:',list03)
print('_'*40)
print('继续删除的元素为:',list03.pop(1)) #指定删除操作,并且返回删除的元素
print('删除后的剩余元素为:',list03)
返回结果:
删除前的元素为: ['jack', 'jane', 'joe', 'black']
________________________________________
默认删除的元素为: black
删除后的剩余元素为: ['jack', 'jane', 'joe']
________________________________________
继续删除的元素为: jane
删除后的剩余元素为: ['jack', 'joe']
del
:指定位置删除,不加位置删除的话,删除元素包括列表名称
list03 = ['jack','jane','joe','black']
print('删除前的元素为:',list03)
print("_"*40)
#del list03 #从内存中彻底删除,包括列表名
del list03[1]
print('删除后剩余的元素为:',list03)
返回结果:
删除前的元素为: ['jack', 'jane', 'joe', 'black']
________________________________________
删除后剩余的元素为: ['jack', 'joe', 'black']
remove()
:当不知道元素索引,只知道元素值的时候,使用
remove()方法删除元素
list03 = ['jack','jane','joe','black']
print('删除前的元素为:',list03)
print("_"*40)
list03.remove('joe') #通过元素值进行删除
print('删除后剩余元素:',list03)
返回结果:
删除前的元素为: ['jack', 'jane', 'joe', 'black']
________________________________________
删除后剩余元素: ['jack', 'jane', 'black']
list.clear()
:用于清空列表,返回空列表
list06 = ['jack','jane','joe','black']
list06.clear()
print(list06)
返回结果:
[]
查找元素
in(存在)
,如果存在那么结果为True,否则为False
list04 = ['jack','jane','joe','black']
name1 = 'jane'
print(name1 in list04) #in存在返回True
name2 = 'blacks'
print(name2 in list04) #in不存在返回False
返回结果:
True
False
not in(不存在)
,如果存在那么结果为False,不存在返回True
list04 = ['jack','jane','joe','black']
name1 = 'jane'
print(name1 not in list04) #not in存在返回False
name2 = 'blacks'
print(name2 not in list04) #not in不存在返回True
返回结果:
False
True
列表函数
len(list)
:查看列表的长度(个数)
list05 = ['jack','jane','joe','black']
print(len(list05)) #返回列表的长度(个数)4
返回结果:
4
max(list)
:返回列表元素中的最大值。默认数值类型的参数,取最大值。字符型的参数,取字母排序靠后者
list05 = ['jack','jane','joe','black','z']
print(max(list05)) #字符返回列表中字符串尾部排序靠后
age = [1,2,22,33]
print(max(age)) #数字返回列表中最大值
返回结果:
z
33
min(list)
:返回列表元素中的最小值。默认数值类型的参数,取最小值。字符型的参数,取字母排序靠前者。
list05 = ['jack','jane','joe','black','a']
print(min(list05)) #字符返回列表中字符串头部排序靠后
age = [1,2,22,33]
print(min(age)) #数字返回列表中最小值
返回结果:
a
1
list.count(obj)
:统计某个元素在列表中出现的次数
list05 = ['jack','jane','joe','black','joe','a']
print(list05.count('joe'))
返回结果:
2
extends(list)
:扩展列表,在一个列表的末尾一次性追加一个新的列表,参数为一个列表
list05 = ['jack','jane','joe','black']
list06 = ['kim','amy']
list05.extend(list06)
print(list05)
返回结果:
['jack', 'jane', 'joe', 'black', 'kim', 'amy']
list.index(obj)
:用于从列表中找出某一个值第一个匹配项的索引位置
list05 = ['jack','jane','joe','black']
print(list05.index('joe'))
返回结果:
2
list.reverse()
:反向列表中的元素,倒序
list05 = ['jack','jane','joe','black']
list05.reverse()
print(list05)
返回结果:
['black', 'joe', 'jane', 'jack']
list.sort()
:对列表进行排序,该方法没有返回值。更改的是原数组
list06 = [4,2,8,9,10]
list06.sort()
print(list06)
返回结果:
[2, 4, 8, 9, 10]
list.copy()
:复制列表
list06 = ['jack','jane','joe','black']
print("复制前:",list06)
print('-'*40)
print("复制后:",list06.copy())
返回结果:
复制前: ['jack', 'jane', 'joe', 'black']
----------------------------------------
复制后: ['jack', 'jane', 'joe', 'black']
字符串常用函数
Python字符串(string)常用函数
find
:检测字符串是否包含指定字符,如果存在则返回开始的索引值,否则返回-1
str1 = 'hello world'
print(str1.find('w')) #存在,则返回是该字符串位置
print(str1.find('z')) #不存在,则返回-1
返回结果:
6
-1
index
:检测字符串是否包含指定字符,若果存在返回开始的索引值,否则提示错误信息
str1 = 'hello world'
print(str1.index('d')) #存在,则返回该字符串位置
print(str1.index('z')) #不存在,提示错误信息
返回结果:
10
print(str1.index('z')) #不存在,提示错误信息
ValueError: substring not found
count
:返回字符串指定索引范围内[start,end]出现的次数
str1 = 'hello world'
print(str1.count('o')) #统计该字符串出现的次数
print(str1.count('l',2,10)) #指定位置查找,指定第2到第10位字符串之间
返回结果:
2
3
replace
:替换,将str1替换成str2,如果指定count,则不超过count次
str1 = 'hello world hello python'
print(str1.replace('hello','go out')) #将hello替换为go out
返回结果:
go out world go out python
split
:切割,指定值进行切割
str1 = 'hello world hello python hello china hello hello hello hello'
print(str1.split('o')) #指定字符进行切割,默认输出到列表中
print(str1.split('o',3)) #指定字符串进行切割,从指定位置之后的不进行切割
返回结果:
['hell', ' w', 'rld hell', ' pyth', 'n hell', ' china hell', ' hell', ' hell', ' hell', '']
['hell', ' w', 'rld hell', ' python hello china hello hello hello hello']
capitalize
:将字符串的首字母大写
str1 = 'hello world hello python'
print(str1.capitalize())
返回结果:
Hello world hello python
title
:将字符串中每个单词的首字母进行大写
str1 = 'hello world'
print(str1.title()) #将每个单词的首字母大写
返回结果:
Hello World
startswith
:检查字符串是否是指定字符开头,是则返回True,否则返回False
str1 = 'hello world hello china'
print(str1.startswith('hello')) #是,则返回True
print(str1.startswith('world')) #否,则返回False
返回结果:
True
False
endswith
:检查字符串是否是指定字符结尾,是则返回True,否则返回False
str1 = 'hello world hello china'
print(str1.endswith('china')) #是,则返回Ture
print(str1.endswith('hello')) #否,则返回False
返回结果:
True
False
lower
:将字符串转换为小写
str1 = 'Hello World HELLO CHINA'
print(str1.lower()) #将字符串转换为小写
返回结果:
hello world hello china
upper
:将字符串转换为大写
str1 = 'hello world hello china'
print(str1.upper()) #将字符串转换为大写
返回结果:
HELLO WORLD HELLO CHINA
ljust
:返回一个字符串左对齐,并使用空格填充至长度width的新字符串
str1 = 'hello'
print(str1.ljust(10)) #左对齐,字符右侧由空格填充至指定长度
返回结果:
hello #选中查看效果
rjust
:返回一个字符串右对齐,并使用空格填充至长度width的新字符串
str1 = 'hello'
print(str1.rjust(10)) #右对齐,字符左侧由空格填充至指定长度
返回结果:
hello #选中查看效果
center
:返回一个源字符串居中,并使用空格填充至长度width的新字符串
str1 = 'hello'
print(str1.center(15)) #居中对齐,字符左右两侧由空格填充至指定长度
返回结果:
hello #选中查看效果
lstrip
:去除字符串左边空白字符
str1 = ' hello'
print(str1) #默认输出字符串结果左边携带空格字符
print(str1.lstrip()) #去除字符串左边空格后结果
返回结果:
hello
hello
rstrip
:去除字符串右边空白字符
str1 = 'hello '
print(str1) #默认输出字符串结果右边携带空格字符
print(str1.rstrip()) #去除字符串右边空格后结果
返回结果:
hello #默认情况
hello
strip
:去除字符串两遍空白字符
str1 = ' hello '
print(str1) #默认输出字符串结果左右两遍携带空格字符
print(str1.strip()) #去除后字符串左右两遍空格后结果
返回结果:
hello #默认情况
hello
partition
:可以根据指定将字符串进行分割,成为三个部分
str1 = 'hello world hello china'
print(str1.partition('world')) #指定字符串进行分割为三部分
返回结果:
('hello ', 'world', ' hello china')
join
:在str2中每个两个字符中间面插入str1中内容,构造出一个新的字符串
str1 = '_'
str2 = ['hello','world','hello'] #在每两个字符中间插入一个str1中内容,使之组成新的字符
print(str1.join(str2))
返回结果:
hello_world_hello
isspace
:如果str1中只包含空格,则返回True,否则返回False
str1 = ' '
str2 = ' hello'
print(str1.isspace())
print(str2.isspace())
返回结果:
True
False
isdigit
:如果str1只包含数字则返回True,否则返回False
str1 = 'a123'
str2 = '123'
print(str1.isdigit()) #返回False,包含字母
print(str2.isdigit()) #返回True,只包含数字
返回结果:
False
True
isalnum
:如果str1所有字符都是字母或数字则返回True,否则返回False
str1 = 'a123'
print(str1.isalnum()) #返回True,只包含数字
返回结果:
True
isalpha
:如果str1所有字符都是都是字母,则返回True,否则返回False
str1 = 'abc'
print(str1.isalpha()) #返回True,只包含字母
返回结果:
True
Nginx介绍及安装
一、Nginx简介
Nginx是一款由俄罗斯开发的开源高性能HTTP服务器和反向代理服务器,同时支持IMAP/POP3/SMTP代理服务,其性能优势显著,官网上称:单台Nginx服务器可以处理50000并发;
特点:高性能,稳定,消耗硬件资源小、能够处理大并发,主要用于静态的解析,动静液面的分离;
优势
- 作为web代理服务器,Nginx处理静态文件、索引文件以及自动索引效率非常高
- 作为代理服务器,Nginx可以实现无缓存的反向代理加速,提高网站运行速度
- 作为负载均衡服务器,Nginx既可以在内部直接支持rails和PHP,也可以支持HTTP代理服务器,对外进行服务。同事支持简单的容错和利用算法进行负载均衡。
- 在性能反面:Nginx在实现上非常注重效率它采用内核Poll模型,可以支持更多的并发连接,最大可以支持50000个并发连接数的响应,而且占用很低的内存资源
- 在性能方面:Nginx采取分阶段资源分配技术,是的对CPU于内存的占用率非常低。Nginx官方便是Nginx保持10000个没有活动的连接,这些连接只占2.5M内存,因此类似DOS这样的攻击对Nginx基本上是没有任何作用的
- 在高可用方面:Nginx支持热部署,启动速度特别迅速,因此可以在不间断服务的情况下,对软件版本或者配置进行升级,即使运行数月也无需重新启动,几乎可以做到7*24小时的不间断运行
二、Nginx实现原理
-
Nginx核心组件
- 核心模块:HTTP模块、EVENT事件模块、MAIL模块
- 基础模块:HTTP Access模块、HTTP FastCGI模块、HTTP Rewrite模块
- 第三方模块:HTTP Upstream Request Hash模块、Notice模块、HTTP Access Key模块
-
Nginx模块分类(基于功能)
-
Nginx的进程模型:
单工作进程模式:除主进程外,还有一个工作进程,工作进程是单线程的,默认为此模式;
多工作进程模式:每个工作进程包含多个线程;
-
master进程:
- 接收外界传递给Nginx的信号,进而管理服务的状态等;
- 管理worker进程,向各worker进程发送信号,监控worker进程的运行状态,当worker进程异常情况下退出后,会自动重新启动新的worker进程;
- master进程充当整个进程组与用户的交互接口,同时对进程进行监护。它不需要处理网络事件,不负责业务的执行,只会通过管理worker进程来实现重启服务、平滑升级、更换日志文件、配置文件实时生效等功能。
-
worker进程:
处理基本的网络事件,多个worker进程之间是对等的,他们同等竞争来自客户端的请求,各进程互相之间是独立的。一个请求,只可能在一个worker进程中处理,一个worker进程,不可能处理其它进程的请求。worker进程的个数是可以设置的,一般我们会设置与机器cpu核心数一致;Nginx实现原理:http://blog.csdn.net/hguisu/article/details/8930668
三、Nginx支持高并发的原因
-
I/O模型之select
- 每个连接对应一个描述。select模型受限于 FD_SETSIZE(即进程最大打开的描述符数),linux2.6.35为1024,实际上linux每个进程所能打开描数字的个数仅受限于内存大小,然而在设计select的系统调用时,却是参考FD_SETSIZE的值。可通过重新编译内核更改此值,但不能根治此问题,对于百万级的用户连接请求即便增加相应进程数,仍显得杯水车薪;
- select每次请求都会扫描一个文件描述符的集合,这个集合的大小是作为select第一个参数传入的值。但是每个进程所能打开文件描述符若是增加了,扫描的效率也将减小;
- 内核到用户空间,采用内存复制方式传递信息,这样就增加了不必要的复制延迟;
-
I/O模型之epoll模型
-
请求无文件描述字大小限制,仅与内存大小相关;
-
epoll返回时已经明确的知道哪个socket fd发生了什么事件,不用像select那样再一个个比对;
-
内核到用户空间,采用共享内存方式传递消息,使用mmap加速内核与用户空间的消息传递;
-
apache:Apache 2.2.9之前只支持select模型,2.2.9之后支持epoll模型;
Nginx:支持epoll模型;
-
四、Nginx安装
-
Nginx下载官网http://nginx.org/
-
安装
[root@localhost ~]# yum -y install pcre-devel zlib-devel
[root@localhost ~]# useradd -M -s /sbin/nologin nginx
[root@localhost ~]# tar xf nginx-1.22.0.tar.gz
[root@localhost nginx-1.22.0]# ./configure --prefix=/data/nginx --user=nginx --group=nginx --with-http_stub_status_module
注解:
--prefix=/usr/local/nginx ##指定安装位置
--user=nginx --group=nginx ##指定运行服务的用户和组
--with-http_stub_status_module ##开启状态监听模块
--conf-path= ##指向配置文件存放位置
--error-log-path= ##指向错误日志存放位置
--pid-path= ##指向pid文件存放位置
--with-rtsig_module ##启用rtsig模块支持(实时信号)
--with-select_module ##启用select模块支持(一种轮询模式,不推荐在高载环境下使用)禁用:--without-select_module
--with-http_ssl_module ##启用ngx_http_ssl_module支持(使支持https请求,需已安装openssl)
--with-http_xslt_module ##启用ngx_http_xslt_module支持(过滤转换XML请求)
--with-http_image_filter_module ##启用ngx_http_image_filter_module支持(传输JPEG/GIF/PNG 图片的一个过滤器)(默认为不启用,要用到gd库)
--with-http_gzip_static_module ##启用ngx_http_gzip_static_module支持(在线实时压缩输出数据流)
--with-http_degradation_module ##启用ngx_http_degradation_module支持(允许在内存不足的情况下返回204或444码)
--without-http_access_module ##禁用ngx_http_access_module支持(该模块提供了一个简单的基于主机的访问控制,允许或拒绝基于ip地址)
--without-http_auth_basic_module ##禁用ngx_http_auth_basic_module(该模块是可以使用用户名和密码基于http基本认证方法,来保护你的站点或其部分内容)
---without-http_rewrite_module ##禁用ngx_http_rewrite_module支持(该模块允许使用正则表达式改变URL)
--without-http_fastcgi_module ##禁用ngx_http_fastcgi_module支持(该模块允许Nginx 与FastCGI 进程交互,并通过传递参数来控制FastCGI 进程工作。)
[root@localhost nginx-1.22.0]# make && make install
[root@localhost nginx-1.22.0]# ls /data/nginx
conf html logs sbin
- 启动
[root@localhost data]# /data/nginx/sbin/nginx
- 优化Nginx启动服务,可以不用做这种方式
[root@localhost data]# ln -s /data/nginx/sbin/nginx /usr/local/sbin/
[root@localhost data]# vi /etc/init.d/nginx
#!/bin/bash
# chkconfig: - 99 20
# description: Nginx Server Control Script
NP="/data/nginx/sbin/nginx"
NPF="/data/nginx/logs/nginx.pid"
case "$1" in
start)
$NP;
if [ $? -eq 0 ]
then
echo "nginx is starting!! "
fi
;;
stop)
kill -s QUIT $(cat $NPF)
if [ $? -eq 0 ]
then
echo "nginx is stopping!! "
fi
;;
restart)
$0 stop
$0 start
;;
reload)
kill -s HUP $(cat $NPF)
if [ $? -eq 0 ]
then
echo "nginx config file is reload! "
fi
;;
*)
echo "Usage: $0 {start|stop|restart|reload}"
exit 1
esac
exit 0
[root@localhost data]# chmod +x /etc/init.d/nginx
[root@localhost data]# chkconfig --add nginx
[root@localhost data]# chkconfig nginx on
[root@localhost data]# /etc/init.d/nginx start #start/stop/restart/reload
- 开启Nginx的状态监听模块
[root@localhost ~]# vi /data/nginx/conf/nginx.conf ##编辑配置文件在server中添加如下行:
47 location /status {
48 stub_status on;
49 access_log off;
50 }
[root@localhost ~]# /data/nginx/sbin/nginx -t #检查配置是否正确
[root@localhost ~]# /data/nginx/sbin/nginx -s reload #重新加载配置文件
http { ##http服务配置区域
include mime.types; ##指定文件扩展名和文件类型映射表
default_type application/octet-stream; ##指定文件类型
charset utf-8; ##指定字符集
server_names_hash_bucket_size 128; ##服务器名字的hash表大小
client_header_buffer_size 2k; ##客户端请求头部buffer大小
large_client_header_buffers 4 4k; ##指定客户端请求中较大的消息头的缓存数量和大小
client_max_body_size 8m; ##指定客户端请求的单个文件的最大字节数
sendfile on; ##开启高效传输模式
tcp_nopush on; ##防止网络阻塞
keepalive_timeout 60; ##客户端连接超时时间
#FastCGI相关参数是为了改善网站的性能:减少资源占用,提高访问速度。
fastcgi_cache_path /usr/local/nginx/fastcgi_cache levels=1:2 ##配置fastcgi缓存路径和目录结构等级
keys_zone=TEST:10m inactive=5m; ##关键字区域存储时间和非活动删除时间
fastcgi_connect_timeout 300; ##连接到后端FastCGI的超时时间
fastcgi_send_timeout 300; ##向FastCGI传送请求的超时时间
fastcgi_read_timeout 300; ##接收FastCGI应答的超时时间
fastcgi_buffer_size 4k; ##指定读取FastCGI应答第一部分需要多大的缓冲区
fastcgi_buffers 8 4k; ##指定本地需要用多少和多大的缓冲区来缓冲FastCGI的应答请求
fastcgi_busy_buffers_size 8k; ##通常为fastcgi_buffer_size大小的两倍
fastcgi_temp_file_write_size 8k; ##写入缓存文件时使用多大的数据块,大小同上
fastcgi_cache TEST; ##开启Fastcgi的缓存并且为其指定一个名称
fastcgi_cache_valid 200 302 1h; ##指定不同的状态码,其缓存的时间
fastcgi_cache_valid 301 1d;
fastcgi_cache_valid any 1m;
fastcgi_cache_min_uses 1; ##URL经过被访问多少次将被缓存
fastcgi_cache_use_stale error timeout invalid_header http_500; ##指定什么情况下不进行缓存
open_file_cache max=204800 inactive=20s; ##指定缓存文件最大数量,经过多长时间文件没有被请求后则删除缓存,
open_file_cache_min_uses 1; ##指令中的inactive参数时间内文件的最少使用次数,如果超过这个数字,文件更改信息一直是在缓存中打开的;
open_file_cache_valid 30s; ##指定多长时间检查一次缓存的有效信息,检查该缓存的源文件是否发生变化修改等;
tcp_nodelay on; ## nagle算法,有需要发送的就立即发送,连接转换为长连接时使用;
server_tokens off; ##禁用版本号
gzip on; ##开启gzip压缩
gzip_min_length 1k; ##指定最小压缩文件的大小
gzip_buffers 4 16k; ##指定压缩缓冲区的个数和大小
gzip_http_version 1.0; ##指定压缩版本
gzip_comp_level 2; ##指定压缩等级1-9,9等级最高
gzip_types text/plain application/x-javascript text/css application/xml; ##指定压缩文件类型
gzip_vary on; ##前端缓存服务器缓存经过压缩的页面
log_format access '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" $http_x_forwarded_for';
##配置日志格式,具体变量表示请结合百度,日志格式为access
- location语法
语法规则: location [=|~|~*|^~] /uri/ { … }
=:表示精确匹配,这个优先级也是最高的
^~:表示url以某个常规字符串开头,理解为匹配 url路径即可。
~ :表示区分大小写的正则匹配
~*:表示不区分大小写的正则匹配(和上面的唯一区别就是大小写)
!~和!~*:分别为区分大小写不匹配及不区分大小写不匹配的正则
/ :通用匹配,任何请求都会匹配到,默认匹配.
优先级排序: = > ^~ >
常用的正则表达式:
* ##重复0次或者多次
? ##重复0次或者1次
+ ##重复1次或多次
. ##匹配除换行符号之外的所有字符
(a|b) ##匹配a或b
^ ##以...开头
$ ##以...结尾
{n} ##重复n次
{n,} ##重复最少n次
{n,m} ##重复n到m次
\W ##匹配任意不是字母,数字,下划线,汉字的字符
\S ##匹配任意不是空白的字符
\D ##匹配任意非数字的字 符
\B ##匹配不是单词开头或结束的位置
[^x] ##匹配除了x以外的所有字符
[^abcd] ##匹配除了a或b或c或d以外的所有字符
^[abcd] ##匹配除了字符串abcd以外的所有字符
- 安装webbench压力测试工具,进行测试nginx性能
[root@localhost ~]# yum -y install gcc ctags
[root@localhost ~]# wget http://home.tiscali.cz/~cz210552/distfiles/webbench-1.5.tar.gz
[root@localhost ~]# tar xf webbench-1.5.tar.gz -C /data/
[root@localhost ~]# cd /data/webbench-1.5/
[root@localhost webbench-1.5]# mkdir /usr/local/man
[root@localhost webbench-1.5]# make && make install
[root@localhost ~]# webbench -c 10000 -t 5 http://192.168.100.102/index.html ##并发数为10000,时间为5秒
Webbench - Simple Web Benchmark 1.5
Copyright (c) Radim Kolar 1997-2004, GPL Open Source Software.
Benchmarking: GET http://192.168.100.102/index.html
10000 clients, running 5 sec.
Speed=147744 pages/min, 1397500 bytes/sec.
Requests: 12312 susceed, 0 failed.
apache介绍及安装
Linux系统安装Apache
Apache简介
Apache HTTP Server(简称Apache)是Apache软件基金会的一个开放源码的网页服务器,可以在大多数计算机操作系统中运行,由于其多平台和安全性被广泛使用,是最流行的Web服务器端软件之一。它快速、可靠并且可通过简单的API扩展,将Perl/Python等解释器编译到服务器中。
-
特点
模块化设置、开放源代码、跨平台应用、支持多种web编程语言、运行稳定; -
apache的常见三种模式
apache的核心模块叫多路处理模块Multi-Processing Module,简称MPM;-
MPM-prefork:多进程模式,一个进程处理一个连接,每个进程相对来讲都是独立的,这个过程会用到select机制来通知;
-
MPM-work:多进程多线程、一个进程开多个线程、每一个线程处理一个连接,但是通知机制还是select,不过可以接受更多的请求;
-
MPM-enent:worker的升级版、把服务器进程和连接进行分离,基于异步I/O模型。请求过来后进程并不处理请求,而是直接交由其他机制来处理,通过epoll机制来通知请求是否完成;在这个过程中,进程本身一直处于空闲状态,可以一直接收用户请求。可以实现一个进程响应多个用户请求。并且event模式对于keep-alive连接处理也有所优化,event模式有单独的线程处理keep-alive长连接,执行完毕后,又允许它释放。这样增强了高并发场景下的请求处理能力。
-
总结:
不同模式效率不同,主要用于调优、命令httpd -V查看当前使用模式;
httpd2.2版本默认的模式为prefork,httpd2.4版本默认的模式为event
-
Apache安装前准备
1、Apache软件下载
Apache的相关软件包下载地址:http://httpd.apache.org/download.cgi#apache24
2、APR and APR-Util包
截止目前为止,APR and APR-Util的最新版本如下,下载地址:http://apr.apache.org/download.cgi
3、 PCRE包
截止目前为止,PCRE最新的包为8.45,下载地址: https://sourceforge.net/projects/pcre/files/pcre/
4、本次安装所用安装包:
apr-1.7.0.tar.gz
apr-util-1.6.1.tar.gz
httpd-2.4.51.tar.gz
pcre-8.45.tar.gz
Apache安装过程
1.安装依赖包
[root@localhost ~]# yum -y install gcc make pcre-devel openssl-devel expat-devel
2.批量解压安装包
[root@localhost ~]# mkdir /data
[root@localhost ~]# for i in *.tar.gz -C /data; do tar xf $i;done
3.将apr和apr-util源码与httpd源码合并
[root@localhost ~]# cp -ar /data/apr-1.7.0 /data/httpd-2.4.53/srclib/apr
[root@localhost ~]# cp -ar /data/apr-util-1.6.1 /data/httpd-2.4.53/srclib/apr-util
4.判断是否存在且创建
[root@localhost ~]# [ -a /data/apache ]||mkdir -p /data/apache
5.编译并安装
[root@localhost ~]# cd httpd-2.4.51/
[root@localhost httpd-2.4.53]#./configure --prefix=/data/apache --enable-so --enable-ssl --enable-cgi --enable-rewrite --with-zlib --with-pcre --with-included-apr --enable-modules=most --enable-mpms-shared=all --with-mpm=prefork
[root@localhost httpd-2.4.51]# make -j 8 &&make install
注释:
--prefix=/data/apache 指定安装位置;
--enable-so 支持动态共享模块;
--enable-ssl 支持ssl;
--enable-cgi 开启cgi通用网管接口;
--enable-rewrite 支持url重写;
--with-zlib 支持 zlib ;
--with-pcre 支持 pcre ;
--with-included-apr 支持apr ;
--enable-modules=most 编译成二进制是安装常用模块;
--enable-mpms-shared=all 安装apache的所有工作模式;
--with-mpm=prefork 指定apache工作模式
6.修改httpd.conf中ServerName www.example.com:80
[root@localhost ~]# vi /data/apache/conf/httpd.conf
#ServerName www.example.com:80
修改为
ServerName localhost:80
7.启动并验证
[root@localhost ~]# /data/apache/bin/apachectl start
[root@localhost bin]# netstat -utpln |grep 80
tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN 47848/httpd
[root@localhost bin]# netstat -ant |awk '/^tcp/{S[$NF]++}END{for(a in S) print a,S[a]}'
LISTEN 3
ESTABLISHED 2
注解:
CLOSED 无连接是活动的或正在进行
LISTEN 服务器在等待进入呼叫
SYN_RECV 一个连接请求已经到达,等待确认
SYN_SENT 应用已经开始,打开一个连接
ESTABLISHED 正常数据传输状态/当前并发连接数
FIN_WAIT1 应用说它已经完成
FIN_WAIT2 另一边已同意释放
ITMED_WAIT 等待所有分组死掉
CLOSING 两边同时尝试关闭
TIME_WAIT 另一边已初始化一个释放
LAST_ACK 等待所有分组死掉