一、前言

   Swap分区,即交换区,系统在物理内存不够时,与Swap进行交换。 其实,Swap的调整对Linux服务器,特别是Web服务器的性能至关重要。通过调整Swap,有时可以越过系统性能瓶颈,节省系统升级费用。Swap分区在系统的物理内存不够用的时候,把物理内存中的一部分空间释放出来,以供当前运行的程序使用。那些被释放的空间可能来自一些很长时间没有什么操作的程序,这些被释放的空间被临时保存到Swap分区中,等到那些程序要运行时,再从Swap分区中恢复保存的数据到内存中。

二、配置

1.查看swap的命令

# free -m       
# top
# swapon -s


2.以文件的方式创建swap分区

# dd if=/dev/zero of=/swap_file bs=1M count=512  
# ll -h /swap_file
-rw-r--r--. 1 root root 512M Mar 18 01:33 /swap_file
# mkswap -f /swap_file     //格式化
# swapon /swap_file        //启动
# swapon -s                //查看
Filename                Type        Size    Used    Priority
/dev/sda3               partition   2064376   0       -1
/swap_file              file        524280    0       -2
# vim /etc/fstab           //开机挂载
 /swap_file   swap   swap   defaults  0 0
# reboot
# swapon -s                //查看
Filename                Type        Size    Used    Priority
/dev/sda3              partition   2064376    0       -1
/swap_file              file        524280    0       -2             
# swapoff /swap_file       //关闭
# swapon -s
Filename                Type        Size    Used    Priority
/dev/sda3             partition   2064376    0        -1


3.以分区的方式创建swap分区

# fdisk /dev/sdb
Command (m for help): n
Command action
   e   extended
   p   primary partition (1-4)
p
Partition number (1-4): 2
First cylinder (133-261, default 133):
Last cylinder, +cylinders or +size{K,M,G} (133-261, default 261): +512M
Command (m for help): t
Partition number (1-4): 2
Hex code (type L to list codes): L
Hex code (type L to list codes): 82      //swap id
Changed system type of partition 2 to 82 (Linux swap / Solaris)
Command (m for help): p
   Device Boot      Start         End      Blocks   Id  System
/dev/sdb1               1         132     1060258+  83  Linux
/dev/sdb2             133         198      530145   82  Linux swap / Solaris
Command (m for help): w
WARNING: Re-reading the partition table failed with error 16: Device or resource busy.
The kernel still uses the old table. The new table will be used at
the next reboot or after you run partprobe(8) or kpartx(8)
Syncing disks.
# reboot
# cat /proc/partitions
major minor  #blocks  name
   8        0   15728640 sda
   8        1     307200 sda1
   8        2   13356032 sda2
   8        3    2064384 sda3
   8       16    2097152 sdb
   8       17    1060258 sdb1
   8       18     530145 sdb2
# mkswap /dev/sdb2
# swapon /dev/sdb2
# swapon -s
Filename    Type        Size    Used    Priority
/dev/sda3      partition       2064376    0   -1
/dev/sdb2      partition        530136    0   -2
# vim /etc/fstab
 /dev/sdb2   swap   swap   defaults  0 0