首页 文章 精选 留言 我的

精选列表

搜索[基础搭建],共10000篇文章
优秀的个人博客,低调大师

rhel6上搭建lnmp架构以及遇到的一些错误并排除方法

先装好rhel6.5 配置好实验环境 关掉NetworkManager,并停止掉开机自启动 [root@duwensql~]#serviceNetworkManagerstop [root@duwensql~]#chkconfig--listNetworkManager [root@duwensql~]#chkconfigNetworkManageroff 关掉iptables [root@duwensql~]#iptables-F [root@duwensql~]#serviceiptablessave iptables£o·àe1ò±£′μ/etc/sysconfig/iptables£o[è·¨] [root@duwensql~]#chkconfigiptablesoff 关掉selinux [root@duwensql~]#getenforce Enforcing [root@duwensql~]#setenforce usage:setenforce[Enforcing|Permissive|1|0] [root@duwensql~]#setenforce0 [root@duwensql~]# [root@duwensql~]#vim/etc/selinux/config 打开这个档案以后你可以看到如下的内容,把SELINUX的值改成disabled就好 #ThisfilecontrolsthestateofSELinuxonthesystem. #SELINUX=cantakeoneofthesethreevalues: #enforcing-SELinuxsecuritypolicyisenforced. #permissive-SELinuxprintswarningsinsteadofenforcing. #disabled-NoSELinuxpolicyisloaded. SELINUX=disabled #SELINUXTYPE=cantakeoneofthesetwovalues: #targeted-Targetedprocessesareprotected, #mls-MultiLevelSecurityprotection. SELINUXTYPE=targeted 修改主机名映射,可以不改,但是为了方便还是改下吧 [root@duwensql~]#cat/etc/hosts 127.0.0.1localhostlocalhost.localdomainlocalhost4localhost4.localdomain4 ::1localhostlocalhost.localdomainlocalhost6localhost6.localdomain6 [root@duwensql~]#echo"192.168.20.253duwensql.cnMySQL">>/etc/hosts [root@duwensql~]#cat/etc/hosts 127.0.0.1localhostlocalhost.localdomainlocalhost4localhost4.localdomain4 ::1localhostlocalhost.localdomainlocalhost6localhost6.localdomain6 192.168.20.253duwensql.cnMySQL [root@duwensql~]# 修改主机名,就是编辑下面的这个档案,这里只贴上修改后的内容 [root@duwensql~]#cat/etc/sysconfig/network NETWORKING=yes HOSTNAME=duwensql.cn GATEWAY=192.168.20.2 NTPSERVERARGS=iburst [root@duwensql~]# 配置本地yum源 [root@duwensql~]# [root@duwensql~]#mount/dev/sr0/mnt/ mount:blockdevice/dev/sr0iswrite-protected,mountingread-only [root@duwensql~]#df-h|tail-1 /dev/sr03.6G3.6G0100%/mnt [root@duwensql~]#echo"/dev/sr0/mnt/iso9660defaults00">>/etc/fstab [root@duwensql~]#rm-rf/etc/yum.repos.d/* [root@duwensql~]#cat>/etc/yum.repos.d/rhel6.repo<<EOF >[rhel6-source] >name=rhel6-source >baseurl=file:///mnt >enabled=1 >gpgcheck=0 >EOF [root@duwensql~]#yumcleanall Loadedplugins:product-id,refresh-packagekit,security,subscription-manager ThissystemisnotregisteredtoRedHatSubscriptionManagement.Youcanusesubscription-managertoregister. Cleaningrepos:rhel6-source CleaningupEverything [root@duwensql~]#yumlist 检测依赖环境,包括gcc,gcc-c++,autoconf,automake,zlib ,zlib-devel, openssl ,openssl-devel ,pcre-devel, [root@duwensql~]# [root@duwensql~]#yuminstall-ygccgcc-c++autoconfautomake [root@duwensql~]#yuminstall-yzlibzlib-developensslopenssl-develpcre-devel 为了方便从xshell上传软件包,这里安装一个工具 [root@duwensql~]#rpm/mnt/Packages/lrzsz-0.12.20-27.1.el6.x86_64.rpm-ih warning:/mnt/Packages/lrzsz-0.12.20-27.1.el6.x86_64.rpm:HeaderV3RSA/SHA256Signature,keyIDfd431d51:NOKEY ###########################################[100%] ###########################################[100%] [root@duwensql~]# //上传软件包:nginx-1.6.0.tar.gzmysql-5.5.30.tar.gz php-5.4.14.tar.bz2 [root@duwensql~]#rz zwaitingtoreceive.**B0100000023be50 [root@duwensql~]#ls anaconda-ks.cfginstall.log.syslognginx-1.6.0.tar.gz公共的视频文档音乐 install.logmysql-5.5.30.tar.gzphp-5.4.14.tar.bz2模板图片下载桌面 正式开始安装MySQL了 解压到指定目录/usr/local/src/ [root@duwensql~]# [root@duwensql~]#tar-zxfmysql-5.5.30.tar.gz-C/usr/local/src/ 建一个mysql用户,这里把这个用户显示出来 [root@duwensql~]#tail-1/etc/passwd mysql:x:500:500::/home/mysql:/sbin/nologin [root@duwensql~]# //安装cmake [root@duwensql~]#yuminstall-ycmake 建立mysql的目录 [root@duwensql/]#mkdir/server [root@duwensql~]#cd/usr/local/src/mysql-5.5.30/ [root@duwensqlmysql-5.5.30]#cmake-DCMAKE_INSTALL_PREFIX=/server/mysql-5.5-DMYSQL_UNIX_ADDR=/tmp/mysql.sock-DDEFAULT_CHARSET=utf8-DDEFAULT_COLLATION=utf8_general_ci-DWITH_EXTRA_CHARSERS=all-DWITH_MYISAM_STORAGE_ENGINE=1-DWITH_INNOBASE_STORAGE_ENGINE=1-DWITH_MEMORY_STORAGE_ENGINE=1-DWITH_READLINT=1-DENABLED_LOCAL_INFILE=1-DMYSQL_DATADIR=/server/mysql/data-DMYSQL_USER=mysql //报错啦啦啦啦 CMakeErroratcmake/readline.cmake:83(MESSAGE): Curseslibrarynotfound.Pleaseinstallappropriatepackage, removeCMakeCache.txtandreruncmake.OnDebian/Ubuntu,packagenameislibncurses5-dev,onRedhatandderivatesitisncurses-devel. CallStack(mostrecentcallfirst): cmake/readline.cmake:127(FIND_CURSES) cmake/readline.cmake:217(MYSQL_USE_BUNDLED_LIBEDIT) CMakeLists.txt:269(MYSQL_CHECK_READLINE) --Configuringincomplete,errorsoccurred! //这个错误就是ncurses这个依赖没有装,yum安装一下 [root@duwensqlncurses-5.9]#yum-yinstallncurses-devel //装了那个ncurses依赖,还是报错,就只好把这个CMakeCache.txt找出来干掉了 [root@duwensqlmysql-5.5.30]#find/-nameCMakeCache.txt /usr/local/src/mysql-5.5.30/CMakeCache.txt [root@duwensqlmysql-5.5.30]#rm-rf/usr/local/src/mysql-5.5.30/CMakeCache.txt //OK,现在重新cmake //呐开心不,没有报错了呢!!! 现在make &&make install,过程就不写了 配置运行环境 [root@duwensqlmysql-5.5.30]#cd/server/ [root@duwensqlserver]#ls mysql-5.5 [root@duwensqlserver]#chown-Rmysql:mysql/server/mysql-5.5/ 复制mysql配置文件 [root@duwensqlserver]#cd/etc/ [root@duwensqletc]#llmy.cnf -rw-r--r--.1rootroot2518月92013my.cnf [root@duwensqletc]#mv./my.cnf./my.cnf.back [root@duwensqletc]#cp/usr/local/src/mysql-5.5.30/support-files/my-large.cnf/etc/my.cnf [root@duwensqletc]# 这个步骤是加入开机启动项 [root@duwensqlinit.d]#cp/usr/local/src/mysql-5.5.30/support-files/mysql.server/etc/init.d/mysqld5.5 [root@duwensqlinit.d]#chmod+x./mysqld5.5 [root@duwensqlinit.d]#pwd /etc/init.d [root@duwensqlinit.d]# //这里要改下,大概在第70行 [root@duwensqlinit.d]#vim/etc/init.d/mysqld5.5 [root@duwensqlinit.d]#head-71/etc/init.d/mysqld5.5|tail-7 then basedir=/server/mysql-5.5 bindir=/server/mysql-5.5/bin iftest-z"$datadir" then datadir=/server/mysql-5.5/data fi [root@duwensqlinit.d]# //加入开机启动项 [root@duwensqlinit.d]#chkconfigmysqld5.5on [root@duwensqlinit.d]#chkconfig--listmysqld5.5 mysqld5.50:关闭1:关闭2:启用3:启用4:启用5:启用6:关闭 [root@duwensqlinit.d]# 初始化mysql [root@duwensqlinit.d]#cd/usr/local/src/mysql-5.5.30/scripts/ [root@duwensqlscripts]#chmod+xmysql_install_db [root@duwensqlscripts]#./mysql_install_db--defaults-file=/etc/my.cnf--basedir=/server/mysql-5.5--datadir=/server/mysql-5.5/data--user=mysql InstallingMySQLsystemtables... OK Fillinghelptables... OK Tostartmysqldatboottimeyouhavetocopy support-files/mysql.servertotherightplaceforyoursystem PLEASEREMEMBERTOSETAPASSWORDFORTHEMySQLrootUSER! Todoso,starttheserver,thenissuethefollowingcommands: /server/mysql-5.5/bin/mysqladmin-urootpassword'new-password' /server/mysql-5.5/bin/mysqladmin-uroot-hduwensqlpassword'new-password' Alternativelyyoucanrun: /server/mysql-5.5/bin/mysql_secure_installation whichwillalsogiveyoutheoptionofremovingthetest databasesandanonymoususercreatedbydefault.Thisis stronglyrecommendedforproductionservers. Seethemanualformoreinstructions. YoucanstarttheMySQLdaemonwith: cd/server/mysql-5.5;/server/mysql-5.5/bin/mysqld_safe& YoucantesttheMySQLdaemonwithmysql-test-run.pl cd/server/mysql-5.5/mysql-test;perlmysql-test-run.pl Pleasereportanyproblemswiththe/server/mysql-5.5/scripts/mysqlbugscript! [root@duwensqlscripts]# 开启mysql [root@duwensqlscripts]#/etc/init.d/mysqld5.5start StartingMySQL...[确定] [root@duwensqlscripts]# 测试MySQL //我这里最开始在家目录输入mysql显示没有命令,是因为没有加入环境变量的缘故啦,这里就不写出来了,直接到绝对路径去测试 root@duwensqlmysql-test]#cd/server [root@duwensqlserver]#ls mysql-5.5 [root@duwensqlserver]#cdmysql-5.5/ [root@duwensqlmysql-5.5]#ls binCOPYINGdatadocsincludeINSTALL-BINARYlibmanmysql-testREADMEscriptssharesql-benchsupport-files [root@duwensqlmysql-5.5]#cdbin/ [root@duwensqlbin]#./mysql WelcometotheMySQLmonitor.Commandsendwith;or\g. YourMySQLconnectionidis1 Serverversion:5.5.30-logSourcedistribution Copyright(c)2000,2013,Oracleand/oritsaffiliates.Allrightsreserved. OracleisaregisteredtrademarkofOracleCorporationand/orits affiliates.Othernamesmaybetrademarksoftheirrespective owners. Type'help;'or'\h'forhelp.Type'\c'toclearthecurrentinputstatement. mysql>showdatabases; +--------------------+ |Database| +--------------------+ |information_schema| |mysql| |performance_schema| |test| +--------------------+ 4rowsinset(0.04sec) mysql> ctrl + c 退出 给他加个环境变量吧 [root@duwensql~]#echo$PATH /usr/lib64/qt-3.3/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin [root@duwensql~]#PATH="$PATH":/server/mysql-5.5/bin/ 设置mysql的root账户密码,并测试登陆 [root@duwensql~]#mysqladmin-urootpassword'123456' [root@duwensql~]#mysql-uroot-p123456 WelcometotheMySQLmonitor.Commandsendwith;or\g. YourMySQLconnectionidis4 Serverversion:5.5.30-logSourcedistribution Copyright(c)2000,2013,Oracleand/oritsaffiliates.Allrightsreserved. OracleisaregisteredtrademarkofOracleCorporationand/orits affiliates.Othernamesmaybetrademarksoftheirrespective owners. Type'help;'or'\h'forhelp.Type'\c'toclearthecurrentinputstatement. mysql> ctrl + c 退出 MySQL安装完了 来安装nginx吧 解压 [root@duwensql~]#tar-zxfnginx-1.6.0.tar.gz 编译 [root@duwensqlnginx-1.6.0]#./configure--prefix=server/nginx-1.6.0--user=nginx--group=nginx--with-http_dav_module--with-http_stub_status_module--with-http_addition_module--with-http_sub_module--with-http_flv_module--with-http_mp4_module 结果太多就不写了,放一个图 make&&make install [root@duwensqlnginx-1.6.0]#make-j4&&makeinstall 开始配置 [root@duwensqlnginx-1.2.8]#pwd /server/nginx-1.2.8 [root@duwensqlnginx-1.2.8]#vimconf/nginx.conf 第二行加 usernginxnginx; 然后加下面的内容,括号{前面有空格 location~\.php${ roothtml; fastcgi_pass127.0.0.1:9000; fastcgi_indexindex.php; fastcgi_paramSCRIPT_FILENAME/server/nginx-1.2.8/html$fastcgi_script_name; includefastcgi_params; } 大概的位置如下图 启动服务 [root@duwensqlnginx-1.2.8]#/server/nginx-1.2.8/sbin/nginx 把服务加入开机启动 [root@duwensqlnginx-1.2.8]#echo'/server/nginx-1.2.8/sbin/nginx&'>>/etc/rc.local [root@duwensqlnginx-1.2.8]# 测试下 测试配置文件和重新加载配置文件 [root@duwensqlnginx-1.2.8]#/server/nginx-1.2.8/sbin/nginx-t nginx:theconfigurationfile/server/nginx-1.2.8/conf/nginx.confsyntaxisok nginx:configurationfile/server/nginx-1.2.8/conf/nginx.conftestissuccessful [root@duwensqlnginx-1.2.8]#/server/nginx-1.2.8/sbin/nginx-sreload 来安装PHP 给PHP添加扩展模块:libmcrypt-2.5.8.tar.gz 1、 让 PHP 编译支持这个功能 2、 生成扩展模块 3、 --with-mcrypt=/usr/local/ 安装libmcrypt库 [root@duwensql~]#tar-zxflibmcrypt-2.5.8.tar.gz [root@duwensql~]#cdlibmcrypt-2.5.8 [root@duwensqllibmcrypt-2.5.8]#./configure--prefix=/usr/local/ [root@duwensqllibmcrypt-2.5.8]#echo$? 0 [root@duwensqllibmcrypt-2.5.8]#make-j4&&makeinstall 加个环境 [root@duwensqllibmcrypt-2.5.8]#yum-yinstallphp-pear 解压以及编译 //在这一步出了好多好多错误,始料不及啊,本文把错误和解决贴上,如果还是不明白的话可以直接搜索错误,这里就不写了 [root@duwensql~]#tarjxfphp-5.4.14.tar.bz2-C/usr/local/src/ [root@duwensql~]#cd/usr/local/src/php-5.4.14/ [root@duwensqlphp-5.4.14]#./configure--prefix=/server/php-5.4-nginx--with-config-file-path=/server/php-5.4-nginx--with-mysql=/server-5.5/--with-mysqli=/server/mysql-5.5/bin/mysql_config--with-iconv-dir--with-freetype-dir--with-jpeg-dir--with-png-dir--with-zlib--with-libxml-dir=/usr--enable-xml--disable-rpath--enable-bcmath--enable-shmop--enable-sysvsem--enable-inline-optimization--with-curl--with-curlwrappers--enable-mbregex--enable-fpm--enable-mbstring--with-gd--enable-gd-native-ttf--with-openssl--with-mhash--enable-pcntl--enable-sockets--with-xmlrpc--enable-zip--enable-soap--with-mcrypt=/usr/local/ 报错1 ####### configure:error:xml2-confignotfound.Pleasecheckyourlibxml2installation. [root@duwensqlphp-5.4.14]# 解决1 [root@duwensqlphp-5.4.14]#yum-yinstalllibxml2* 重新编译 [root@duwensqlphp-5.4.14]#./configure--prefix=/server/php-5.4-nginx--with-config-file-path=/server/php-5.4-nginx--with-mysql=/server/mysql-5.5/--with-mysqli=/server/mysql-5.5/bin/mysql_config--with-iconv-dir--with-freetype-dir--with-jpeg-dir--with-png-dir--with-zlib--with-libxml-dir=/usr--enable-xml--disable-rpath--enable-bcmath--enable-shmop--enable-sysvsem--enable-inline-optimization--with-curl--with-curlwrappers--enable-mbregex--enable-fpm--enable-mbstring--with-gd--enable-gd-native-ttf--with-openssl--with-mhash--enable-pcntl--enable-sockets--with-xmlrpc--enable-zip--enable-soap--with-mcrypt=/usr/local/ 报错2 checkingifweshouldusecURLforurlstreams...yes checkingforcURLindefaultpath...notfound configure:error:Pleasereinstallthelibcurldistribution- easy.hshouldbein<curl-dir>/include/curl/ [root@duwensqlphp-5.4.14]# 解决2: [root@duwensqlphp-5.4.14]#yum-yinstallcurl-devel 重新编译 [root@duwensqlphp-5.4.14]#./configure--prefix=/server/php-5.4-nginx--with-config-file-path=/server/php-5.4-nginx--with-mysql=/server/mysql-5.5/--with-mysqli=/server/mysql-5.5/bin/mysql_config--with-iconv-dir--with-freetype-dir--with-jpeg-dir--with-png-dir--with-zlib--with-libxml-dir=/usr--enable-xml--disable-rpath--enable-bcmath--enable-shmop--enable-sysvsem--enable-inline-optimization--with-curl--with-curlwrappers--enable-mbregex--enable-fpm--enable-mbstring--with-gd--enable-gd-native-ttf--with-openssl--with-mhash--enable-pcntl--enable-sockets--with-xmlrpc--enable-zip--enable-soap--with-mcrypt=/usr/local/ 报错3 checkingwhethertoenableJIS-mappedJapanesefontsupportinGD...no checkingforfabsf...yes checkingforfloorf...yes configure:error:jpeglib.hnotfound 解决3:*不要丢了 [root@duwensqlphp-5.4.14]#yum-yinstalllibjpeg* 再次编译 [root@duwensqlphp-5.4.14]./configure--prefix=/server/php-5.4-nginx--with-config-file-path=/server/php-5.4-nginx--with-mysql=/server/mysql-5.5/--with-mysqli=/server/mysql-5.5/bin/mysql_config--with-iconv-dir--with-freetype-dir--with-jpeg-dir--with-png-dir--with-zlib--with-libxml-dir=/usr--enable-xml--disable-rpath--enable-bcmath--enable-shmop--enable-sysvsem--enable-inline-optimization--with-curl--with-curlwrappers--enable-mbregex--enable-fpm--enable-mbstring--with-gd--enable-gd-native-ttf--with-openssl--with-mhash--enable-pcntl--enable-sockets--with-xmlrpc--enable-zip--enable-soap--with-mcrypt=/usr/local/ 报错4: checkingforjpeg_read_headerin-ljpeg...yes Ifconfigurefailstry--with-vpx-dir=<DIR> configure:error:png.hnotfound. [root@duwensqlphp-5.4.14]# 解决4:*不要丢了 [root@duwensqlphp-5.4.14]#yum-yinstalllibpng* 再次编译 [root@duwensqlphp-5.4.14]#./configure--prefix=/server/php-5.4-nginx--with-config-file-path=/server/php-5.4-nginx--with-mysql=/server/mysql-5.5/--with-mysqli=/server/mysql-5.5/bin/mysql_config--with-iconv-dir--with-freetype-dir--with-jpeg-dir--with-png-dir--with-zlib--with-libxml-dir=/usr--enable-xml--disable-rpath--enable-bcmath--enable-shmop--enable-sysvsem--enable-inline-optimization--with-curl--with-curlwrappers--enable-mbregex--enable-fpm--enable-mbstring--with-gd--enable-gd-native-ttf--with-openssl--with-mhash--enable-pcntl--enable-sockets--with-xmlrpc--enable-zip--enable-soap--with-mcrypt=/usr/local/ 报错5: configure:error:freetype.hnotfound. 解决5:*不要丢掉了 [root@duwensqlphp-5.4.14]#yum-yinstallfreetype* 再次编译 [root@duwensqlphp-5.4.14]#./configure--prefix=/server/php-5.4-nginx--with-config-file-path=/server/php-5.4-nginx--with-mysql=/server/mysql-5.5/--with-mysqli=/server/mysql-5.5/bin/mysql_config--with-iconv-dir--with-freetype-dir--with-jpeg-dir--with-png-dir--with-zlib--with-libxml-dir=/usr--enable-xml--disable-rpath--enable-bcmath--enable-shmop--enable-sysvsem--enable-inline-optimization--with-curl--with-curlwrappers--enable-mbregex--enable-fpm--enable-mbstring--with-gd--enable-gd-native-ttf--with-openssl--with-mhash--enable-pcntl--enable-sockets--with-xmlrpc--enable-zip--enable-soap--with-mcrypt=/usr/local/ 报错6: checkingforspecifiedlocationoftheMySQLUNIXsocket...no configure:error:CannotfindMySQLheaderfilesunder/server-5.5/. NotethattheMySQLclientlibraryisnotbundledanymore! 这个应该是指定路径错误,改下 再次编译 [root@duwensqlphp-5.4.14]#./configure--prefix=/server/php-5.4-nginx--with-config-file-path=/server/php-5.4-nginx--with-mysql=/server/mysql-5.5/--with-mysqli=/server/mysql-5.5/bin/mysql_config--with-iconv-dir--with-freetype-dir--with-jpeg-dir--with-png-dir--with-zlib--with-libxml-dir=/usr--enable-xml--disable-rpath--enable-bcmath--enable-shmop--enable-sysvsem--enable-inline-optimization--with-curl--with-curlwrappers--enable-mbregex--enable-fpm--enable-mbstring--with-gd--enable-gd-native-ttf--with-openssl--with-mhash--enable-pcntl--enable-sockets--with-xmlrpc--enable-zip--enable-soap--with-mcrypt=/usr/local/ 报错7: configure:error:wrongmysqllibraryversionorlibnotfound.Checkconfig.logformoreinformation. 解决7: “=/server/mysql-5.5/bin/mysql_config”删掉试试 改好以后的执行: [root@duwensqlphp-5.4.14]#./configure--prefix=/server/php-5.4-nginx--with-config-file-path=/server/php-5.4-nginx--with-mysql=/server/mysql-5.5/--with-mysqli--with-iconv-dir--with-freetype-dir--with-jpeg-dir--with-png-dir--with-zlib--with-libxml-dir=/usr--enable-xml--disable-rpath--enable-bcmath--enable-shmop--enable-sysvsem--enable-inline-optimization--with-curl--with-curlwrappers--enable-mbregex--enable-fpm--enable-mbstring--with-gd--enable-gd-native-ttf--with-openssl--with-mhash--enable-pcntl--enable-sockets--with-xmlrpc--enable-zip--enable-soap--with-mcrypt=/usr/local/ 历经千辛万苦啊 这里贴上一些参数的意思 --with-iconv-dir #字符集转换 需要的扩展模块 –without-iconv 关闭 iconv 函数,种字符集间的转换 –with-freetype-dir 打开对 freetype 字体库的支持 –with-jpeg-dir 打开对 jpeg 图片的支持 –with-png-dir 打开对 png 图片的支持 –with-libxml-dir 打开 libxml2 库的支持 –disable-rpath 关闭额外的运行库文件 –enable-bcmath 打开图片大小调整,用到 zabbix 监控的时候用到了这个模块 下面 是make && make install [root@duwensqlphp-5.4.14]#make-j4&&makeinstall 生成配置文件 [root@duwensql~]#cp/usr/local/src/php-5.4.14/php.ini-production/server/php-5.4-nginx/php.ini 生成php-fpm配置文件 [root@duwensql~]#cp/server/php-5.4-nginx/etc/php-fpm.conf.default/server/php-5.4-nginx/etc/php-fpm.conf 生成php-fpm启动脚本 [root@duwensql~]#cp/usr/local/src/php-5.4.14/sapi/fpm/init.d.php-fpm/etc/init.d/php-fpm [root@duwensql~]#chmod+x/etc/init.d/php-fpm [root@duwensql~]#/etc/init.d/php-fpmstart Startingphp-fpmdone [root@duwensql~]#netstat-anptu|grep9000 tcp00127.0.0.1:90000.0.0.0:*LISTEN76616/php-fpm [root@duwensql~]# 测试php [root@duwensql~]#vim/server/nginx-1.2.8/html/a.php [root@duwensql~]#cat/server/nginx-1.2.8/html/a.php <?php phpinfo(); ?> [root@duwensql~]# 效果图如下 The End!

优秀的个人博客,低调大师

基础到实战:一文吃透 JS Tuples 与 Records 的所有核心用法

JavaScript 中的 Tuples(Tuples)与 Records(Records)提供了不可变的、基于值的数据结构,能简化状态管理、提升性能并增强代码的可预测性。 JavaScript 一直在持续进化以满足现代开发需求,其最新更新往往紧跟函数式编程和不可变数据处理的趋势。Tuples 与 Records 作为语言即将新增的两个特性,旨在简化不可变性的实现,同时提升开发效率与体验。本文将深入探讨这两个新特性,包括它们的设计目的、语法、优势及应用场景。 一、什么是 Tuples 与 Records? 1. Tuples(元组) Tuples 是不可变的有序值列表。和数组类似,Tuples 可以存储多个元素,但不可变性确保了数据一旦创建就无法修改------这保证了数据一致性,非常适合对数据完整性和可预测性要求高的场景。 2. Records(记录) Records 是不可变的键值对结构,类似 JavaScript 中的对象,但它是只读的:一旦创建,其属性和值就无法修改。 二、Tuples 与 Records 的核心特性 1. 不可变性(Immutability) Tuples 和 Records 都是完全不可变的,甚至嵌套元素也无法修改。 示例: const tuple = #[1, 2, 3]; const record = #{ name: "Alice", age: 25 }; // 以下操作都会抛出错误 tuple[0] = 99; // 错误:Tuples是不可变的 record.name = "Bob"; // 错误:Records是不可变的 2. 值语义(Value Semantics) 和数组、对象的"引用比较"不同,Tuples 与 Records 采用"值比较", equality 检查更符合直觉。 示例: const tuple1 = #[1, 2, 3]; const tuple2 = #[1, 2, 3]; console.log(tuple1 === tuple2); // true(值相同则相等) 3. 类型安全(Type Safety) Tuples 严格要求元素的顺序和类型一致性。结合 TypeScript 使用时,开发者可以定义明确的类型约束,进一步保证使用的可预测性。 4. 内存高效(Memory Efficiency) 不可变性让 JavaScript 引擎能优化内存使用:由于值永远不会改变,相同数据的引用可以在应用中重复利用,减少内存开销。 5. 语法(Syntax) Tuples 使用 #[...] 语法: const myTuple = #[1, 'hello', true]; Records 使用 #{...} 语法: const myRecord = #{ key: 'value', id: 123 }; 三、Tuples 与 Records 在 TypeScript 中的应用 即将推出的 Tuples 与 Records 能与 TypeScript 无缝集成,带来更强的类型安全、可预测性和可维护性。借助 TS 的强类型能力,这些不可变结构可以强制严格的数据格式,防止意外修改。 1. Tuples 的类型安全 TS 中的 Tuples 本就支持固定长度数组的类型校验,结合 JavaScript 的不可变 Tuples 后,安全性进一步提升。 示例:带类型的 Tuples 声明 const myTuple: #[number, string, boolean] = #[1, "hello", true]; // 合法访问 const num: number = myTuple[0]; // 允许 // 非法修改(Tuples不可变) myTuple[1] = "world"; // 错误:无法赋值给只读元素 核心优势: TS 确保元素遵循指定的类型顺序; 防止意外修改,维护数据完整性。 2. Records 的类型安全 Records 类似对象,但支持深层不可变。TS 的类型系统允许定义严格的键值结构,确保值在使用过程中始终一致。 示例:带类型的 Records 声明 const userRecord: #{ name: string, age: number, active: boolean } = #{ name: "Alice", age: 30, active: true }; // 类型安全的属性访问 const username: string = userRecord.name; // 尝试修改Records(会失败) userRecord.age = 31; // 错误:无法赋值给只读属性 核心优势: TS 强制严格的属性类型; 杜绝意外的属性修改。 3. TS 的类型推断 TS 能自动推断 Tuples 与 Records 的类型,减少显式注解的需求。 示例:类型推断 const config = #{ apiEndpoint: "https://api.example.com", retries: 3 }; // TS自动推断类型:#{ apiEndpoint: string, retries: number } console.log(typeof config.apiEndpoint); // "string" 4. 函数签名中的应用 Tuples 与 Records 非常适合作为函数的参数和返回值,确保输入输出符合预期结构。 示例 1:使用 Records 的函数 function getUserInfo(user: #{ id: number, name: string }): string { return `用户:${user.name}(ID:${user.id})`; } const user = #{ id: 101, name: "Bob" }; console.log(getUserInfo(user)); // 输出:用户:Bob(ID:101) 示例 2:返回 Tuples 的函数 function getCoordinates(): #[number, number] { return #[40.7128, -74.0060]; // 纽约坐标 } const coords = getCoordinates(); console.log(coords[0]); // 40.7128 5. 结合 TS 工具类型 TS 的工具类型(如Readonly、Pick、Partial)可以与 Tuples、Records 结合使用,增加灵活性。 示例:对 Records 使用Readonly type User = #{ id: number, name: string }; const readonlyUser: Readonly<User> = #{ id: 1, name: "Charlie" }; // 尝试修改Records readonlyUser.name = "David"; // 错误:无法修改只读属性 四、不同领域的实际应用场景 Tuples 与 Records 通过增强数据完整性、可预测性和效率,在多个行业中展现出独特优势。下面看看它们在不同领域的具体应用。 1. 金融应用 金融领域对数据完整性和不可变性要求极高,以防止未授权修改并符合监管标准。 示例:处理不可变的金融交易 const transaction: #{ id: number, amount: number, currency: string, completed: boolean } = #{ id: 12345, amount: 1000, currency: "USD", completed: false }; // 不修改原数据,创建处理后的新交易 const processedTransaction = #{ ...transaction, completed: true }; console.log(processedTransaction.completed); // true 行业优势: 防止交易数据被意外或未授权修改; 不可变性保证了审计追踪的可靠性。 2. 数据分析 处理大型数据集时,数据一致性至关重要。Tuples 可用于表示固定结构的报表数据。 示例:存储不可变的报表数据 const reportEntry: #[string, number, boolean] = #["销售额", 5000, true]; // 安全提取报表值 const [category, revenue, approved] = reportEntry; console.log(`分类:${category},收入:${revenue}`); 行业优势: 确保报表数据在处理过程中不被篡改; 便于 Records 的比较和去重。 3. 游戏开发 在游戏中,Tuples 可用于存储固定长度的数据,如坐标、RGB 颜色值或动画状态。 示例:用 Tuples 处理玩家坐标 const playerPosition: #[number, number] = #[100, 200]; // 移动玩家到新位置(创建新Tuples,而非修改原数据) const newPosition = #[200, 300]; console.log(`X:${playerPosition[0]}, Y:${playerPosition[1]}`); 行业优势: 固定长度、不可变的数据结构提升性能; 防止意外修改导致物理计算出错。 4. 配置管理 在大型应用中,Records 非常适合定义静态、不可修改的配置值。 示例:应用配置 const appConfig = #{ appName: "MyApp", maxUsers: 1000, theme: "dark" }; // 安全使用配置 console.log(appConfig.theme); // "dark" 行业优势: 防止关键配置被意外修改; 提升配置文件的可读性和可维护性。 5. 版本控制与数据一致性 对于需要向后兼容的应用,Records 能确保不同版本间的数据一致性。 示例:维护向后兼容 const oldVersionUser = #{ id: 1, name: "John" }; const newVersionUser = #{ ...oldVersionUser, email: "john@example.com" }; console.log(newVersionUser); // #{ id: 1, name: "John", email: "john@example.com" } 行业优势: 扩展数据结构时保持向后兼容; 维护旧版本时避免意外修改。 五、Tuples/Records vs Object.freeze():核心区别 Object.freeze() 和 Records 都能创建不可变数据结构,但在性能、深层不可变性、值语义和易用性上存在显著差异。选择哪种方式,取决于你的应用场景。 特性 Object.freeze() Records( Records) 不可变性 浅层(需手动实现深层冻结) 深层(自动实现) 语义比较 基于引用 基于值 性能 深层冻结时开销大 原生优化,效率高 语法 繁琐(需手动调用,嵌套需递归) 简洁(#{...} 原生语法) 1. 不可变性差异 Object.freeze():浅层不可变 Object.freeze() 只冻结对象的顶层属性,嵌套对象仍可修改,需手动递归冻结。 示例: const obj = { name: "Alice", address: { city: "New York" } }; // 冻结对象 Object.freeze(obj); // 尝试修改顶层属性(严格模式下报错) obj.name = "Bob"; // 静默失败或报错 // 嵌套属性仍可修改 obj.address.city = "Los Angeles"; // 成功 console.log(obj.address.city); // 输出:Los Angeles(已被修改) 修复方案:手动实现深层冻结函数 function deepFreeze(object) { Object.keys(object).forEach(key => { if (typeof object[key] === "object" && object[key] !== null) { deepFreeze(object[key]); // 递归冻结嵌套对象 } }); return Object.freeze(object); } const deeplyFrozenObj = deepFreeze(obj); deeplyFrozenObj.address.city = "San Francisco"; // 现在会报错 console.log(deeplyFrozenObj.address.city); // 输出:New York(未被修改) Records:深层不可变 Records 自动支持深层不可变,无需手动处理嵌套结构。 示例: const record = #{ name: "Alice", address: #{ city: "New York" } }; // 尝试修改任何属性都会报错 record.name = "Bob"; // 类型错误:无法赋值给只读属性 record.address.city = "Los Angeles"; // 类型错误:无法赋值给只读属性 console.log(record.address.city); // 输出:New York(未被修改) 核心结论 : Object.freeze() 需要手动递归实现深层不可变,而 Records 原生支持,更安全易用。 2. 引用比较 vs 值比较 Object.freeze():基于引用 冻结的对象仍按引用比较,即使内容相同,不同引用也视为不相等。 示例: const obj1 = Object.freeze({ name: "Alice" }); const obj2 = Object.freeze({ name: "Alice" }); console.log(obj1 === obj2); // 输出:false(引用不同) console.log(obj1.name === obj2.name); // 输出:true(值相同) Records:基于值 Records 按值比较,内容相同则视为相等,无论是否为不同实例。 示例: const record1 = #{ name: "Alice" }; const record2 = #{ name: "Alice" }; console.log(record1 === record2); // 输出:true(值相同) 核心结论 : Records 的值比较更符合直觉,避免了深层比较函数的繁琐。 3. 易用性与性能 更新方式:两者都需通过扩展语法创建新实例,但 Records 的语法更简洁; 性能:Object.freeze() 深层冻结时会有运行时开销,而 Records 是原生优化的不可变结构,性能更优; 语法体验:Records 的 #{...} 语法比手动调用 Object.freeze() 更直观,尤其处理嵌套结构时。 推荐场景 应用场景 推荐方案 简单的浅层不可变需求 Object.freeze()(小型对象) 复杂嵌套数据结构 Records(深层不可变) 频繁的值比较需求 Records(值语义更高效) 六、嵌套 Tuples 与 Records 1. 什么是嵌套结构? 嵌套 Tuples 是"包含其他 Tuples 的 Tuples",嵌套 Records 是"值为其他 Records 的 Records"------它们可以构建深层的不可变数据模型。 示例: const nestedTuple = #[ #[1, 2], #[3, 4] ]; const nestedRecord = #{ user: #{ name: "Alice", address: #{ city: "New York", zip: "10001" } } }; console.log(nestedTuple[0][1]); // 输出:2 console.log(nestedRecord.user.address.city); // 输出:"New York" 2. 为什么要用嵌套结构? 数据完整性:确保深层嵌套数据也不可变; 可预测性:值比较简化状态变化追踪; 可读性:清晰表达复杂的数据关系; 性能:不可变状态管理的内存使用更优。 3. 嵌套结构的更新:不可变原则 由于不可变性,更新嵌套结构需在每一层都使用扩展语法 创建新实例。 示例 1:更新嵌套 Records const user = #{ name: "Alice", details: #{ age: 30, address: #{ city: "Los Angeles", zip: "90001" } } }; // 深层更新城市(每一层都扩展) const updatedUser = #{ ...user, details: #{ ...user.details, address: #{ ...user.details.address, city: "San Francisco" } } }; console.log(updatedUser.details.address.city); // 输出:"San Francisco" 示例 2:用工具函数简化深层更新 // 深层更新Records的工具函数 function updateNestedRecord(record, keyPath, value) { if (keyPath.length === 1) { return #{ ...record, [keyPath[0]]: value }; } return #{ ...record, [keyPath[0]]: updateNestedRecord(record[keyPath[0]], keyPath.slice(1), value) }; } // 调用函数更新邮编 const updatedUserState = updateNestedRecord(user, ["details", "address", "zip"], "10002"); console.log(updatedUserState.details.address.zip); // 输出:"10002" 4. 常见陷阱与规避 陷阱 1:忘记逐层扩展 错误:const updatedUser = #{ ...user, details.address.city: "Seattle" };(语法错误) 解决:必须在每一层嵌套都使用扩展语法(如上面的示例)。 陷阱 2:错误的比较方式 错误:用 == 而非 === 比较 Records(虽然结果可能相同,但推荐用 === 符合值语义设计)。 解决:始终用 === 比较 Tuples/Records。 陷阱 3:访问不存在的嵌套属性 错误:console.log(user.details.phone.number);(phone 未定义,报错) 解决:用可选链 ?. 安全访问:user.details?.phone?.number ?? "未设置"。 七、与现代 JavaScript 模式的结合 Tuples 与 Records 天然契合以"不可变性"为核心的现代开发模式,尤其在状态管理中表现突出。 1. 在 Redux 中使用 Records import { createStore } from "redux"; // 用Records定义初始状态 const initialState = #{ user: #{ name: "Alice", loggedIn: false } }; const reducer = (state = initialState, action) => { switch (action.type) { case "LOGIN": // 不可变更新状态 return #{ ...state, user: #{ ...state.user, loggedIn: true } }; default: return state; } }; const store = createStore(reducer); store.dispatch({ type: "LOGIN" }); console.log(store.getState()); // 输出:#{ user: #{ name: "Alice", loggedIn: true } } 2. 在 React 中使用 Tuples 与 Records 示例 1:Records 作为 React 状态 import React, { useState } from 'react'; const UserProfile = () => { // 用Records存储用户状态 const [user, setUser] = useState(#{ name: "Alice", age: 30 }); const updateAge = () => { // 不可变更新:创建新Records setUser(#{ ...user, age: user.age + 1 }); }; return ( <div> <p>姓名:{user.name}</p> <p>年龄:{user.age}</p> <button onClick={updateAge}>年龄+1</button> </div> ); }; export default UserProfile; 示例 2:Tuples 作为固定长度状态 import React, { useState } from 'react'; const Scoreboard = () => { // 用Tuples存储分数(固定结构) const [scores, setScores] = useState(#[10, 20, 30]); const addScore = () => { // 不可变添加:创建新Tuples setScores(#[...scores, 40]); }; return ( <div> <p>分数:{scores.join(", ")}</p> <button onClick={addScore}>添加分数</button> </div> ); }; export default Scoreboard; 八、如何现在就体验 Tuples 与 Records? Tuples 与 Records 目前仍在开发中,但可以通过 Babel 或 TypeScript 的早期提案插件提前体验。 用 Babel 配置 安装插件: npm install @babel/plugin-proposal-record-and-tuple 2.配置 .babelrc: { "plugins": ["@babel/plugin-proposal-record-and-tuple"] } 九、总结 Tuples 与 Records 是 JavaScript 向"更可靠、更高效"进化的重要一步。它们通过原生支持深层不可变 和值语义,解决了传统数组/对象在状态管理中的痛点,同时无需依赖 Immutable.js 等第三方库。 无论是金融、游戏、数据分析还是前端框架开发,Tuples 与 Records 都能简化代码、减少 bug,并提升性能。现在就可以通过 Babel/TS 提前尝试,为未来的语言标准做好准备!

资源下载

更多资源
优质分享App

优质分享App

近一个月的开发和优化,本站点的第一个app全新上线。该app采用极致压缩,本体才4.36MB。系统里面做了大量数据访问、缓存优化。方便用户在手机上查看文章。后续会推出HarmonyOS的适配版本。

腾讯云软件源

腾讯云软件源

为解决软件依赖安装时官方源访问速度慢的问题,腾讯云为一些软件搭建了缓存服务。您可以通过使用腾讯云软件源站来提升依赖包的安装速度。为了方便用户自由搭建服务架构,目前腾讯云软件源站支持公网访问和内网访问。

Nacos

Nacos

Nacos /nɑ:kəʊs/ 是 Dynamic Naming and Configuration Service 的首字母简称,一个易于构建 AI Agent 应用的动态服务发现、配置管理和AI智能体管理平台。Nacos 致力于帮助您发现、配置和管理微服务及AI智能体应用。Nacos 提供了一组简单易用的特性集,帮助您快速实现动态服务发现、服务配置、服务元数据、流量管理。Nacos 帮助您更敏捷和容易地构建、交付和管理微服务平台。

Spring

Spring

Spring框架(Spring Framework)是由Rod Johnson于2002年提出的开源Java企业级应用框架,旨在通过使用JavaBean替代传统EJB实现方式降低企业级编程开发的复杂性。该框架基于简单性、可测试性和松耦合性设计理念,提供核心容器、应用上下文、数据访问集成等模块,支持整合Hibernate、Struts等第三方框架,其适用范围不仅限于服务器端开发,绝大多数Java应用均可从中受益。

用户登录
用户注册