少年阿賓

          那些青春的歲月

            BlogJava :: 首頁 :: 聯系 :: 聚合  :: 管理
            500 Posts :: 0 Stories :: 135 Comments :: 0 Trackbacks

          #

          Nginx配置文件詳細說明
          在此記錄下Nginx服務器nginx.conf的配置文件說明, 部分注釋收集與網絡.
          #運行用戶
          user www-data;   
          #啟動進程,通常設置成和cpu的數量相等
          worker_processes  1;
          #全局錯誤日志及PID文件
          error_log  /var/log/nginx/error.log;
          pid        /var/run/nginx.pid;
          #工作模式及連接數上限
          events {
              use   epoll;             #epoll是多路復用IO(I/O Multiplexing)中的一種方式,但是僅用于linux2.6以上內核,可以大大提高nginx的性能
              worker_connections  1024;#單個后臺worker process進程的最大并發鏈接數
              # multi_accept on;
          }
          #設定http服務器,利用它的反向代理功能提供負載均衡支持
          http {
               #設定mime類型,類型由mime.type文件定義
              include       /etc/nginx/mime.types;
              default_type  application/octet-stream;
              #設定日志格式
              access_log    /var/log/nginx/access.log;
              #sendfile 指令指定 nginx 是否調用 sendfile 函數(zero copy 方式)來輸出文件,對于普通應用,
              #必須設為 on,如果用來進行下載等應用磁盤IO重負載應用,可設置為 off,以平衡磁盤與網絡I/O處理速度,降低系統的uptime.
              sendfile        on;
              #tcp_nopush     on;
            
              #連接超時時間
              #keepalive_timeout  0;
              keepalive_timeout  65;
              tcp_nodelay        on;
             
              #開啟gzip壓縮
              gzip  on;
              gzip_disable "MSIE [1-6]\.(?!.*SV1)";
              #設定請求緩沖
              client_header_buffer_size    1k;
              large_client_header_buffers  4 4k;
              include /etc/nginx/conf.d/*.conf;
              include /etc/nginx/sites-enabled/*;
            
             #設定負載均衡的服務器列表
               upstream mysvr {
              #weigth參數表示權值,權值越高被分配到的幾率越大
              #本機上的Squid開啟3128端口
              server 192.168.8.1:3128 weight=5;
              server 192.168.8.2:80  weight=1;
              server 192.168.8.3:80  weight=6;
              }

             server {
              #偵聽80端口
                  listen       80;
                  #定義使用www.xx.com訪問
                  server_name  www.xx.com;
                  #設定本虛擬主機的訪問日志
                  access_log  logs/www.xx.com.access.log  main;
              #默認請求
              location / {
                    root   /root;      #定義服務器的默認網站根目錄位置
                    index index.php index.html index.htm;   #定義首頁索引文件的名稱
                    fastcgi_pass  www.xx.com;
                   fastcgi_param  SCRIPT_FILENAME  $document_root/$fastcgi_script_name;
                    include /etc/nginx/fastcgi_params;
                  }
              # 定義錯誤提示頁面
              error_page   500 502 503 504 /50x.html; 
                  location = /50x.html {
                  root   /root;
              }
              #靜態文件,nginx自己處理
              location ~ ^/(images|javascript|js|css|flash|media|static)/ {
                  root /var/www/virtual/htdocs;
                  #過期30天,靜態文件不怎么更新,過期可以設大一點,如果頻繁更新,則可以設置得小一點。
                  expires 30d;
              }
              #PHP 腳本請求全部轉發到 FastCGI處理. 使用FastCGI默認配置.
              location ~ \.php$ {
                  root /root;
                  fastcgi_pass 127.0.0.1:9000;
                  fastcgi_index index.php;
                  fastcgi_param SCRIPT_FILENAME /home/www/www$fastcgi_script_name;
                  include fastcgi_params;
              }
              #設定查看Nginx狀態的地址
              location /NginxStatus {
                  stub_status            on;
                  access_log              on;
                  auth_basic              "NginxStatus";
                  auth_basic_user_file  conf/htpasswd;
              }
              #禁止訪問 .htxxx 文件
              location ~ /\.ht {
                  deny all;
              }
              
               }
          }


          #以上是一些基本的配置,使用Nginx最大的好處就是負載均衡
          #如果要使用負載均衡的話,可以修改配置http節點如下:
          #設定http服務器,利用它的反向代理功能提供負載均衡支持
          http {
               #設定mime類型,類型由mime.type文件定義
              include       /etc/nginx/mime.types;
              default_type  application/octet-stream;
              #設定日志格式
              access_log    /var/log/nginx/access.log;
              #省略上文有的一些配置節點
              #。。。。。。。。。。
              #設定負載均衡的服務器列表
               upstream mysvr {
              #weigth參數表示權值,權值越高被分配到的幾率越大
              server 192.168.8.1x:3128 weight=5;#本機上的Squid開啟3128端口
              server 192.168.8.2x:80  weight=1;
              server 192.168.8.3x:80  weight=6;
              }
             upstream mysvr2 {
              #weigth參數表示權值,權值越高被分配到的幾率越大
              server 192.168.8.x:80  weight=1;
              server 192.168.8.x:80  weight=6;
              }
             #第一個虛擬服務器
             server {
              #偵聽192.168.8.x的80端口
                  listen       80;
                  server_name  192.168.8.x;
                #對aspx后綴的進行負載均衡請求
              location ~ .*\.aspx$ {
                   root   /root;      #定義服務器的默認網站根目錄位置
                    index index.php index.html index.htm;   #定義首頁索引文件的名稱
                    proxy_pass  http://mysvr ;#請求轉向mysvr 定義的服務器列表
                    #以下是一些反向代理的配置可刪除.
                    proxy_redirect off;
                  
             #后端的Web服務器可以通過X-Forwarded-For獲取用戶真實IP
                    proxy_set_header Host $host;
                    proxy_set_header X-Real-IP $remote_addr;
                    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                    client_max_body_size 10m;    #允許客戶端請求的最大單文件字節數
                    client_body_buffer_size 128k;  #緩沖區代理緩沖用戶端請求的最大字節數,
                    proxy_connect_timeout 90;  #nginx跟后端服務器連接超時時間(代理連接超時)
                    proxy_send_timeout 90;        #后端服務器數據回傳時間(代理發送超時)
                    proxy_read_timeout 90;         #連接成功后,后端服務器響應時間(代理接收超時)
                    proxy_buffer_size 4k;             #設置代理服務器(nginx)保存用戶頭信息的緩沖區大小
                    proxy_buffers 4 32k;               #proxy_buffers緩沖區,網頁平均在32k以下的話,這樣設置
                    proxy_busy_buffers_size 64k;    #高負荷下緩沖大小(proxy_buffers*2)
                    proxy_temp_file_write_size 64k;  #設定緩存文件夾大小,大于這個值,將從upstream服務器傳
                 }
               }
          }

          posted @ 2013-01-03 14:52 abin 閱讀(487) | 評論 (0)編輯 收藏

           開發的應用采用F5負載均衡交換機,F5將請求轉發給5臺hp unix服務器,每臺服務器有多個webserver實例,對外提供web服務和socket等接口服務。之初,曾有個小小的疑問為何不采用開源的apache、Nginx軟件負載,F5設備動輒幾十萬,價格昂貴?自己一個比較幼稚的問題,后續明白:F5是操作于IOS網絡模型的傳輸層,Nginx、apache是基于http反向代理方式,位于ISO模型的第七層應用層。直白些就是TCP UDP 和http協議的區別,Nginx不能為基于TCP協議的應用提供負載均衡。


                了解了二者之間的區別于應用場景,對Nginx產生濃厚的興趣,閱讀張宴的<實戰Nginx>(這個85年的小伙子年輕有為羨慕+妒忌),搞明白了大致原理和配置,Ubuntu10.10,window下對Nginx+tomcat負載均衡做了配置嘗試,將全部請求轉發到tomcat,并未做靜態,動態分開,圖片防盜鏈等配置。
          Nginx 介紹


               Nginx (發音同 engine x)是一款輕量級的Web 服務器/反向代理服務器及電子郵件(IMAP/POP3)代理服務器,并在一個BSD-like 協議下發行。  其特點是占有內存少,并發能力強,事實上nginx的并發能力確實在同類型的網頁伺服器中表現較好.目前中國大陸使用nginx網站用戶有:新浪、網易、 騰訊,另外知名的微網志Plurk也使用nginx。


              上面的全是Nginx介紹基本上是廢話,下面轉入正題,圖文結合展示基本配置,首先是window環境、其次是Ubuntu環境(Vbox虛擬)。本文主要基于Nginx下配置兩臺tomcat,結構如下圖:

           

          Window xp環境:Nginx+Tomcat6

          1、下載地址

                 http://nginx.org/en/download.html ,這里我們推薦下載穩定版(stable versions),本文采用nginx-0.8.20。


          2、目錄結構


                Nginx-

                         |_  conf   配置目錄

                         |_  contrib

                         |_  docs 文檔目錄

                         |_  logs  日志目錄

                         |_  temp 臨時文件目錄

                         |_  html 靜態頁面目錄

                         |_  nginx.exe 主程序


                window下安裝Nginx極其簡單,解壓縮到一個無空格的英文目錄即可(個人習慣,擔心中文出問題),雙擊nginx啟動,這里我安裝到:D:\server目錄,下面涉及到的tomcat也安裝在此目錄。

             

          DOS環境啟動

           

          若果想停止nginx,dos環境運行命令:nginx -s stop


          3、nginx.conf配置


             Nginx配置文件默認在conf目錄,主要配置文件為nginx.conf,我們安裝在D:\server\nginx-0.8.20、默認主配置文件為D:\server\nginx-0.8.20\nginx.conf。下面是nginx作為前端反向代理服務器的配置。

          #Nginx所用用戶和組,window下不指定
          #user  niumd niumd;
          #工作的子進程數量(通常等于CPU數量或者2倍于CPU)
          worker_processes  2;
          #錯誤日志存放路徑
          #error_log  logs/error.log;
          #error_log  logs/error.log  notice;
          error_log  logs/error.log  info;
          #指定pid存放文件
          pid        logs/nginx.pid;
          events {
          #使用網絡IO模型linux建議epoll,FreeBSD建議采用kqueue,window下不指定。
          #use epoll;
          #允許最大連接數
          worker_connections  2048;
          }
          http {
          include       mime.types;
          default_type  application/octet-stream;
          #定義日志格式
          #log_format  main  '$remote_addr - $remote_user [$time_local] $request '
          #                  '"$status" $body_bytes_sent "$http_referer" '
          #                  '"$http_user_agent" "$http_x_forwarded_for"';
          #access_log  off;
          access_log  logs/access.log;
          client_header_timeout  3m;
          client_body_timeout    3m;
          send_timeout           3m;
          client_header_buffer_size    1k;
          large_client_header_buffers  4 4k;
          sendfile        on;
          tcp_nopush      on;
          tcp_nodelay     on;
          #keepalive_timeout  75 20;
          include    gzip.conf;
          upstream localhost {
          #根據ip計算將請求分配各那個后端tomcat,許多人誤認為可以解決session問題,其實并不能。
          #同一機器在多網情況下,路由切換,ip可能不同
          #ip_hash;
          server localhost:18081;
          server localhost:18080;
          }
          server {
          listen       80;
          server_name  localhost;
          location / {
          proxy_connect_timeout   3;
          proxy_send_timeout      30;
          proxy_read_timeout      30;
          proxy_pass http://localhost;
          }
          }
          }

           
             代理設置如下:

          proxy_redirect          off;
          proxy_set_header        Host $host;
          proxy_set_header        X-Real-IP $remote_addr;
          proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
          client_max_body_size    10m;
          client_body_buffer_size 128k;
          proxy_connect_timeout   300;
          proxy_send_timeout      300;
          proxy_read_timeout      300;
          proxy_buffer_size       4k;
          proxy_buffers           4 32k;
          proxy_busy_buffers_size 64k;
          proxy_temp_file_write_size 64k;
          


             gzip壓縮相關配置如下:

          gzip              on;
          gzip_min_length      1000;
          gzip_types         text/plain text/css application/x-javascript;
          

           
            4、Tomcat配置


             對于tomcat大家都很熟悉,只需要修改server.xml配置文件即可,這里我們以apache-tomcat-6.0.14為例,分別在server目錄,解壓縮并命名為:apache-tomcat-6.0.14_1、apache-tomcat-6.0.14_2。


              第一處端口修改:

          <!--  修改port端口:18006 倆個tomcat不能重復,端口隨意,別太小-->
          <Server port="18006" shutdown="SHUTDOWN">
          

           
             第二處端口修改:

          <!-- port="18081" tomcat監聽端口,隨意設置,別太小 -->
          <Connector port="18081" protocol="HTTP/1.1"
          connectionTimeout="20000"
          redirectPort="8443" />
           


             第三處端口修改:

          <Connector port="8009" protocol="AJP/1.3" redirectPort="8443" />
          


             Engine元素增加jvmRoute屬性:

          <Engine name="Catalina" defaultHost="localhost" jvmRoute="tomcat1">
          

           
              兩個tomcat的端口別重復,保證能啟動起來,另一個tomcat配置希捷省略,監聽端口為18080,附件中我們將上傳所有的配置信息。


          5、驗證配置與測試負載均衡


              首先測試nginx配置是否正確,測試命令:nginx -t  (默認驗證:conf\nginx.conf),也可以指定配置文件路徑。

           此例nginx安裝目錄:D:\server\nginx-0.8.20,dos環境下圖畫面成功示例:

             其次驗證tomcat,啟動兩個tomcat,不出現端口沖突即為成功(tomcat依賴的java等搞“挨踢”的就廢話不說了);

           

              最后驗證配置負載均衡設置,http://localhost/ 或http://localhost/index.jsp 。我修改了index.jsp頁面,增加日志輸出信息,便于觀察。注意:左上角小貓頭上的:access tomcat2、access tomcat1。說明訪問了不同的tomcat。

            

           
               至此window下nginx+tomcat負載均衡配置結束,關于tomcat Session的問題通常是采用memcached,或者采用nginx_upstream_jvm_route ,他是一個 Nginx 的擴展模塊,用來實現基于 Cookie 的 Session Sticky 的功能。如果tomcat過多不建議session同步,server間相互同步session很耗資源,高并發環境容易引起Session風暴。請根據自己應用情況合理采納session解決方案。



           作者:niumd 

            Blog:http://ari.iteye.com

          posted @ 2013-01-03 14:51 abin 閱讀(602) | 評論 (0)編輯 收藏

          //nginx.conf


          #user  nobody;
          worker_processes  1;

          #error_log  logs/error.log;
          #error_log  logs/error.log  notice;
          error_log  logs/error.log  info;

          pid        logs/nginx.pid;


          events {
              worker_connections  1024;
          }


          http {
              include       mime.types;
              default_type  application/octet-stream;

              #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
              #                  '$status $body_bytes_sent "$http_referer" '
              #                  '"$http_user_agent" "$http_x_forwarded_for"';

              #access_log  logs/access.log  main;

              sendfile        on;
              #tcp_nopush     on;

              #keepalive_timeout  0;
              keepalive_timeout  65;

              #gzip  on;
              include    gzip.conf; 
              upstream localhost { 
                #根據ip計算將請求分配各那個后端tomcat,許多人誤認為可以解決session問題,其實并不能。 
                #同一機器在多網情況下,路由切換,ip可能不同 
                #ip_hash;  
                server localhost:16300  weight=5; 
                server localhost:16400  weight=1; 
               } 

              server {
                  listen       80;
                  server_name  localhost;

                  #charset koi8-r;

                  #access_log  logs/host.access.log  main;

                  location / {
                proxy_connect_timeout   3; 
                              proxy_send_timeout      30; 
                              proxy_read_timeout      30; 
                              proxy_pass http://localhost
                      root   html;
                      index  index.html index.htm;
                  }

                  #error_page  404              /404.html;

                  # redirect server error pages to the static page /50x.html
                  #
                  error_page   500 502 503 504  /50x.html;
                  location = /50x.html {
                      root   html;
                  }

                  # proxy the PHP scripts to Apache listening on 127.0.0.1:80
                  #
                  #location ~ \.php$ {
                  #    proxy_pass   http://127.0.0.1;
                  #}

                  # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
                  #
                  #location ~ \.php$ {
                  #    root           html;
                  #    fastcgi_pass   127.0.0.1:9000;
                  #    fastcgi_index  index.php;
                  #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
                  #    include        fastcgi_params;
                  #}

                  # deny access to .htaccess files, if Apache's document root
                  # concurs with nginx's one
                  #
                  #location ~ /\.ht {
                  #    deny  all;
                  #}
              }


              # another virtual host using mix of IP-, name-, and port-based configuration
              #
              #server {
              #    listen       8000;
              #    listen       somename:8080;
              #    server_name  somename  alias  another.alias;

              #    location / {
              #        root   html;
              #        index  index.html index.htm;
              #    }
              #}


              # HTTPS server
              #
              #server {
              #    listen       443;
              #    server_name  localhost;

              #    ssl                  on;
              #    ssl_certificate      cert.pem;
              #    ssl_certificate_key  cert.key;

              #    ssl_session_timeout  5m;

              #    ssl_protocols  SSLv2 SSLv3 TLSv1;
              #    ssl_ciphers  ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP;
              #    ssl_prefer_server_ciphers   on;

              #    location / {
              #        root   html;
              #        index  index.html index.htm;
              #    }
              #}

          }





          //在%NGINX_HOME%/conf/下面新增proxy.conf
          proxy_redirect          off; 
          proxy_set_header        Host $host; 
          proxy_set_header        X-Real-IP $remote_addr; 
          proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for; 
          client_max_body_size    10m; 
          client_body_buffer_size 128k; 
          proxy_connect_timeout   300; 
          proxy_send_timeout      300; 
          proxy_read_timeout      300; 
          proxy_buffer_size       4k; 
          proxy_buffers           4 32k; 
          proxy_busy_buffers_size 64k; 
          proxy_temp_file_write_size 64k;




          //在%NGINX_HOME%/conf/下面新增gzip.conf
          gzip              on; 
          gzip_min_length      1000; 
          gzip_types         text/plain text/css application/x-javascript;





          //tomcat63    %TOMCAT_HOME%/conf/server.xml

          <?xml version='1.0' encoding='utf-8'?>
          <!--
            Licensed to the Apache Software Foundation (ASF) under one or more
            contributor license agreements.  See the NOTICE file distributed with
            this work for additional information regarding copyright ownership.
            The ASF licenses this file to You under the Apache License, Version 2.0
            (the "License"); you may not use this file except in compliance with
            the License.  You may obtain a copy of the License at

                http://www.apache.org/licenses/LICENSE-2.0

            Unless required by applicable law or agreed to in writing, software
            distributed under the License is distributed on an "AS IS" BASIS,
            WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
            See the License for the specific language governing permissions and
            limitations under the License.
          -->
          <!-- Note:  A "Server" is not itself a "Container", so you may not
               define subcomponents such as "Valves" at this level.
               Documentation at /docs/config/server.html
           -->
          <Server port="16305" shutdown="SHUTDOWN">

            <!--APR library loader. Documentation at /docs/apr.html -->
            <Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on" />
            <!--Initialize Jasper prior to webapps are loaded. Documentation at /docs/jasper-howto.html -->
            <Listener className="org.apache.catalina.core.JasperListener" />
            <!-- Prevent memory leaks due to use of particular java/javax APIs-->
            <Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener" />
            <!-- JMX Support for the Tomcat server. Documentation at /docs/non-existent.html -->
            <Listener className="org.apache.catalina.mbeans.ServerLifecycleListener" />
            <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" />

            <!-- Global JNDI resources
                 Documentation at /docs/jndi-resources-howto.html
            -->
            <GlobalNamingResources>
              <!-- Editable user database that can also be used by
                   UserDatabaseRealm to authenticate users
              -->
              <Resource name="UserDatabase" auth="Container"
                        type="org.apache.catalina.UserDatabase"
                        description="User database that can be updated and saved"
                        factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
                        pathname="conf/tomcat-users.xml" />
            </GlobalNamingResources>

            <!-- A "Service" is a collection of one or more "Connectors" that share
                 a single "Container" Note:  A "Service" is not itself a "Container",
                 so you may not define subcomponents such as "Valves" at this level.
                 Documentation at /docs/config/service.html
             -->
            <Service name="Catalina">
           
              <!--The connectors can use a shared executor, you can define one or more named thread pools-->
              <!--
              <Executor name="tomcatThreadPool" namePrefix="catalina-exec-"
                  maxThreads="150" minSpareThreads="4"/>
              -->
             
             
              <!-- A "Connector" represents an endpoint by which requests are received
                   and responses are returned. Documentation at :
                   Java HTTP Connector: /docs/config/http.html (blocking & non-blocking)
                   Java AJP  Connector: /docs/config/ajp.html
                   APR (HTTP/AJP) Connector: /docs/apr.html
                   Define a non-SSL HTTP/1.1 Connector on port 8080
              -->
              <Connector port="16300" protocol="HTTP/1.1"
                         connectionTimeout="20000"
                         redirectPort="8443" />
              <!-- A "Connector" using the shared thread pool-->
              <!--
              <Connector executor="tomcatThreadPool"
                         port="8080" protocol="HTTP/1.1"
                         connectionTimeout="20000"
                         redirectPort="8443" />
              -->          
              <!-- Define a SSL HTTP/1.1 Connector on port 8443
                   This connector uses the JSSE configuration, when using APR, the
                   connector should be using the OpenSSL style configuration
                   described in the APR documentation -->
              <!--
              <Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"
                         maxThreads="150" scheme="https" secure="true"
                         clientAuth="false" sslProtocol="TLS" />
              -->

              <!-- Define an AJP 1.3 Connector on port 8009 -->
              <Connector port="16309" protocol="AJP/1.3" redirectPort="8443" />


              <!-- An Engine represents the entry point (within Catalina) that processes
                   every request.  The Engine implementation for Tomcat stand alone
                   analyzes the HTTP headers included with the request, and passes them
                   on to the appropriate Host (virtual host).
                   Documentation at /docs/config/engine.html -->

              <!-- You should set jvmRoute to support load-balancing via AJP ie :
              <Engine name="Catalina" defaultHost="localhost" jvmRoute="jvm1">        
              -->
              <Engine name="Catalina" defaultHost="localhost" jvmRoute="tomcat63">

                <!--For clustering, please take a look at documentation at:
                    /docs/cluster-howto.html  (simple how to)
                    /docs/config/cluster.html (reference documentation) -->
                <!--
                <Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/>
                -->       

                <!-- The request dumper valve dumps useful debugging information about
                     the request and response data received and sent by Tomcat.
                     Documentation at: /docs/config/valve.html -->
                <!--
                <Valve className="org.apache.catalina.valves.RequestDumperValve"/>
                -->

                <!-- This Realm uses the UserDatabase configured in the global JNDI
                     resources under the key "UserDatabase".  Any edits
                     that are performed against this UserDatabase are immediately
                     available for use by the Realm.  -->
                <Realm className="org.apache.catalina.realm.UserDatabaseRealm"
                       resourceName="UserDatabase"/>

                <!-- Define the default virtual host
                     Note: XML Schema validation will not work with Xerces 2.2.
                 -->
                <Host name="localhost"  appBase="webapps"
                      unpackWARs="true" autoDeploy="true"
                      xmlValidation="false" xmlNamespaceAware="false">

                  <!-- SingleSignOn valve, share authentication between web applications
                       Documentation at: /docs/config/valve.html -->
                  <!--
                  <Valve className="org.apache.catalina.authenticator.SingleSignOn" />
                  -->

                  <!-- Access log processes all example.
                       Documentation at: /docs/config/valve.html -->
                  <!--
                  <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs" 
                         prefix="localhost_access_log." suffix=".txt" pattern="common" resolveHosts="false"/>
                  -->

                </Host>
              </Engine>
            </Service>
          </Server>




          %TOMCAT_HOME%/conf/server.xml

          <?xml version='1.0' encoding='utf-8'?>
          <!--
            Licensed to the Apache Software Foundation (ASF) under one or more
            contributor license agreements.  See the NOTICE file distributed with
            this work for additional information regarding copyright ownership.
            The ASF licenses this file to You under the Apache License, Version 2.0
            (the "License"); you may not use this file except in compliance with
            the License.  You may obtain a copy of the License at

                http://www.apache.org/licenses/LICENSE-2.0

            Unless required by applicable law or agreed to in writing, software
            distributed under the License is distributed on an "AS IS" BASIS,
            WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
            See the License for the specific language governing permissions and
            limitations under the License.
          -->
          <!-- Note:  A "Server" is not itself a "Container", so you may not
               define subcomponents such as "Valves" at this level.
               Documentation at /docs/config/server.html
           -->
          <Server port="16405" shutdown="SHUTDOWN">

            <!--APR library loader. Documentation at /docs/apr.html -->
            <Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on" />
            <!--Initialize Jasper prior to webapps are loaded. Documentation at /docs/jasper-howto.html -->
            <Listener className="org.apache.catalina.core.JasperListener" />
            <!-- Prevent memory leaks due to use of particular java/javax APIs-->
            <Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener" />
            <!-- JMX Support for the Tomcat server. Documentation at /docs/non-existent.html -->
            <Listener className="org.apache.catalina.mbeans.ServerLifecycleListener" />
            <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" />

            <!-- Global JNDI resources
                 Documentation at /docs/jndi-resources-howto.html
            -->
            <GlobalNamingResources>
              <!-- Editable user database that can also be used by
                   UserDatabaseRealm to authenticate users
              -->
              <Resource name="UserDatabase" auth="Container"
                        type="org.apache.catalina.UserDatabase"
                        description="User database that can be updated and saved"
                        factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
                        pathname="conf/tomcat-users.xml" />
            </GlobalNamingResources>

            <!-- A "Service" is a collection of one or more "Connectors" that share
                 a single "Container" Note:  A "Service" is not itself a "Container",
                 so you may not define subcomponents such as "Valves" at this level.
                 Documentation at /docs/config/service.html
             -->
            <Service name="Catalina">
           
              <!--The connectors can use a shared executor, you can define one or more named thread pools-->
              <!--
              <Executor name="tomcatThreadPool" namePrefix="catalina-exec-"
                  maxThreads="150" minSpareThreads="4"/>
              -->
             
             
              <!-- A "Connector" represents an endpoint by which requests are received
                   and responses are returned. Documentation at :
                   Java HTTP Connector: /docs/config/http.html (blocking & non-blocking)
                   Java AJP  Connector: /docs/config/ajp.html
                   APR (HTTP/AJP) Connector: /docs/apr.html
                   Define a non-SSL HTTP/1.1 Connector on port 8080
              -->
              <Connector port="16400" protocol="HTTP/1.1"
                         connectionTimeout="20000"
                         redirectPort="8443" />
              <!-- A "Connector" using the shared thread pool-->
              <!--
              <Connector executor="tomcatThreadPool"
                         port="8080" protocol="HTTP/1.1"
                         connectionTimeout="20000"
                         redirectPort="8443" />
              -->          
              <!-- Define a SSL HTTP/1.1 Connector on port 8443
                   This connector uses the JSSE configuration, when using APR, the
                   connector should be using the OpenSSL style configuration
                   described in the APR documentation -->
              <!--
              <Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"
                         maxThreads="150" scheme="https" secure="true"
                         clientAuth="false" sslProtocol="TLS" />
              -->

              <!-- Define an AJP 1.3 Connector on port 8009 -->
              <Connector port="16409" protocol="AJP/1.3" redirectPort="8443" />


              <!-- An Engine represents the entry point (within Catalina) that processes
                   every request.  The Engine implementation for Tomcat stand alone
                   analyzes the HTTP headers included with the request, and passes them
                   on to the appropriate Host (virtual host).
                   Documentation at /docs/config/engine.html -->

              <!-- You should set jvmRoute to support load-balancing via AJP ie :
              <Engine name="Catalina" defaultHost="localhost" jvmRoute="jvm1">        
              -->
              <Engine name="Catalina" defaultHost="localhost" jvmRoute="tomcat64">

                <!--For clustering, please take a look at documentation at:
                    /docs/cluster-howto.html  (simple how to)
                    /docs/config/cluster.html (reference documentation) -->
                <!--
                <Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/>
                -->       

                <!-- The request dumper valve dumps useful debugging information about
                     the request and response data received and sent by Tomcat.
                     Documentation at: /docs/config/valve.html -->
                <!--
                <Valve className="org.apache.catalina.valves.RequestDumperValve"/>
                -->

                <!-- This Realm uses the UserDatabase configured in the global JNDI
                     resources under the key "UserDatabase".  Any edits
                     that are performed against this UserDatabase are immediately
                     available for use by the Realm.  -->
                <Realm className="org.apache.catalina.realm.UserDatabaseRealm"
                       resourceName="UserDatabase"/>

                <!-- Define the default virtual host
                     Note: XML Schema validation will not work with Xerces 2.2.
                 -->
                <Host name="localhost"  appBase="webapps"
                      unpackWARs="true" autoDeploy="true"
                      xmlValidation="false" xmlNamespaceAware="false">

                  <!-- SingleSignOn valve, share authentication between web applications
                       Documentation at: /docs/config/valve.html -->
                  <!--
                  <Valve className="org.apache.catalina.authenticator.SingleSignOn" />
                  -->

                  <!-- Access log processes all example.
                       Documentation at: /docs/config/valve.html -->
                  <!--
                  <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs" 
                         prefix="localhost_access_log." suffix=".txt" pattern="common" resolveHosts="false"/>
                  -->

                </Host>
              </Engine>
            </Service>
          </Server>





          先啟動nginx,后啟動tomcat。

          首先測試nginx配置是否正確,測試命令:nginx -t  (默認驗證:conf\nginx.conf),也可以指定配置文件路徑。

          其次驗證tomcat,啟動兩個tomcat,不出現端口沖突即為成功(tomcat依賴的java等搞“挨踢”的就廢話不說了);


           

          posted @ 2013-01-03 14:47 abin 閱讀(619) | 評論 (0)編輯 收藏

          post提交模擬

          import java.io.BufferedReader;
          import java.io.BufferedWriter;
          import java.io.IOException;
          import java.io.InputStreamReader;
          import java.io.OutputStreamWriter;
          import java.net.InetAddress;
          import java.net.Socket;
          import java.net.URLEncoder;

          public class TestSocketPost {

              public static void main(String[] args) {
                  BufferedWriter httpPostWriter = null;
                  BufferedReader httpResponse = null;
                  try {
                      // form域的數據.form域的數據必須以鏈接形式發送
                      StringBuffer formDataItems = new StringBuffer();
                      formDataItems.append(URLEncoder.encode("name", "GBK"));
                      formDataItems.append("=");
                      formDataItems.append(URLEncoder.encode("fruitking", "GBK"));
                      formDataItems.append("&");
                      formDataItems.append(URLEncoder.encode("company", "GBK"));
                      formDataItems.append("=");
                      formDataItems.append(URLEncoder.encode("intohotel", "GBK"));
                      String hostname = "localhost";// 主機,可以是域名,也可以是ip地址
                      int port = 8080;// 端口
                      InetAddress addr = InetAddress.getByName(hostname);
                      // 建立連接
                      Socket socket = new Socket(addr, port);
                      // 創建數據提交數據流
                      httpPostWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "GBK"));
                      // 相對主機的請求地址
                      String httpSubmitPath = "/icbcnet/testpostresult.jsp";
                      // 發送數據頭
                      httpPostWriter.write("POST " + httpSubmitPath + " HTTP/1.0\r\n");
                      httpPostWriter.write("Host: socket方式的post提交測試\r\n");
                      httpPostWriter.write("Content-Length: " + formDataItems.length() + "\r\n");
                      httpPostWriter.write("Content-Type: application/x-www-form-urlencoded\r\n");
                      httpPostWriter.write("\r\n"); // 以空行作為分割
                      // 發送數據
                      httpPostWriter.write(formDataItems.toString());
                      httpPostWriter.flush();
                      // 創建web服務器響應的數據流
                      httpResponse = new BufferedReader(new InputStreamReader(socket.getInputStream(), "GBK"));
                      String lineStr = "";
                      while ((lineStr = httpResponse.readLine()) != null) {
                          System.out.println(lineStr);
                      }
                  } catch (Exception e) {
                      e.printStackTrace();
                  } finally {
                      try {
                          if (httpPostWriter != null) {
                              httpPostWriter.close();
                          }
                          if (httpResponse != null) {
                              httpResponse.close();
                          }
                      } catch (IOException e) {
                          e.printStackTrace();
                      }
                  }
              }
          }

          get模擬

          import java.io.BufferedReader;
          import java.io.BufferedWriter;
          import java.io.IOException;
          import java.io.InputStreamReader;
          import java.io.OutputStreamWriter;
          import java.net.InetAddress;
          import java.net.Socket;
          import java.net.URLEncoder;

          public class TestSocketGet {

              public static void main(String[] args) {
                  BufferedWriter httpGetWriter = null;
                  BufferedReader httpResponse = null;
                  try {
                      String hostname = "localhost";// 主機,可以是域名,也可以是ip地址
                      int port = 8080;// 端口
                      InetAddress addr = InetAddress.getByName(hostname);
                      // 建立連接
                      Socket socket = new Socket(addr, port);
                      // 創建數據提交數據流
                      httpGetWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "GBK"));
                      // 相對主機的請求地址
                      StringBuffer httpSubmitPath = new StringBuffer("/icbcnet/testpostresult.jsp?");
                      httpSubmitPath.append(URLEncoder.encode("name", "GBK"));
                      httpSubmitPath.append("=");
                      httpSubmitPath.append(URLEncoder.encode("fruitking", "GBK"));
                      httpSubmitPath.append("&");
                      httpSubmitPath.append(URLEncoder.encode("company", "GBK"));
                      httpSubmitPath.append("=");
                      httpSubmitPath.append(URLEncoder.encode("pubone", "GBK"));
                      httpGetWriter.write("GET " + httpSubmitPath.toString() + " HTTP/1.1\r\n");
                      httpGetWriter.write("Host: socket方式的get提交測試\r\n");
                      httpGetWriter.write("\r\n");
                      httpGetWriter.flush();
                      // 創建web服務器響應的數據流
                      httpResponse = new BufferedReader(new InputStreamReader(socket.getInputStream(), "GBK"));
                      // 讀取每一行的數據.注意大部分端口操作都需要交互數據。
                      String lineStr = "";
                      while ((lineStr = httpResponse.readLine()) != null) {
                          System.out.println(lineStr);
                      }
                  } catch (Exception e) {
                      e.printStackTrace();
                  } finally {
                      try {
                          if (httpGetWriter != null) {
                              httpGetWriter.close();
                          }
                          if (httpResponse != null) {
                              httpResponse.close();
                          }
                      } catch (IOException e) {
                          e.printStackTrace();
                      }
                  }
              }
          }
          posted @ 2012-12-31 12:35 abin 閱讀(2363) | 評論 (0)編輯 收藏

                 Web服務器與客戶端的通信使用HTTP協議(超文本傳輸協議),所以也叫做HTTP服務器。用Java構造Web服務器主要用二個類,java.net.Socket和java.net.ServerSocket,來實現HTTP通信。因此,本文首先要討論的是HTTP協議和這兩個類,在此基礎上實現一個簡單但完整的Web服務器。
            一、超文本傳輸協議
            Web服務器和瀏覽器通過HTTP協議在Internet上發送和接收消息。HTTP協議是一種請求-應答式的協議——客戶端發送一個請求,服務器返回該請求的應答。HTTP協議使用可靠的TCP連接,默認端口是80。HTTP的第一個版本是HTTP/0.9,后來發展到了HTTP/1.0,現在最新的版本是HTTP/1.1。HTTP/1.1由
           RFC 2616 定義(pdf格式)。
            本文只簡要介紹HTTP 1.1的相關知識,但應該足以讓你理解Web服務器和瀏覽器發送的消息。如果你要了解更多的細節,請參考RFC 2616。
            在HTTP中,客戶端/服務器之間的會話總是由客戶端通過建立連接和發送HTTP請求的方式初始化,服務器不會主動聯系客戶端或要求與客戶端建立連接。瀏覽器和服務器都可以隨時中斷連接,例如,在瀏覽網頁時你可以隨時點擊“停止”按鈕中斷當前的文件下載過程,關閉與Web服務器的HTTP連接。
            1.1 HTTP請求
            HTTP請求由三個部分構成,分別是:方法-URI-協議/版本,請求頭,請求正文。下面是一個HTTP請求的例子:
          GET /servlet/default.jsp HTTP/1.1
          Accept: text/plain; text/html
          Accept-Language: en-gb
          Connection: Keep-Alive
          Host: localhost
          Referer: http://localhost/ch8/SendDetails.htm
          User-Agent: Mozilla/4.0 (compatible; MSIE 4.01; Windows 98)
          Content-Length: 33
          Content-Type: application/x-www-form-urlencoded
          Accept-Encoding: gzip, deflate
          userName=JavaJava&userID=javaID

           請求的第一行是“方法-URI-協議/版本”,其中GET就是請求方法,/servlet/default.jsp表示URI,HTTP/1.1是協議和協議的版本。根據HTTP標準,HTTP請求可以使用多種請求方法。例如,HTTP 1.1支持七種請求方法:GET,POST,HEAD,OPTIONS,PUT,DELETE,和TRACE。在Internet應用中,最常用的請求方法是GET和POST。
            URI完整地指定了要訪問的網絡資源,通常認為它相對于服務器的根目錄而言,因此總是以“/”開頭。URL實際上是
          URI 一種類型。最后,協議版本聲明了通信過程中使用的HTTP協議的版本。
            請求頭包含許多有關客戶端環境和請求正文的有用信息。例如,請求頭可以聲明瀏覽器所用的語言,請求正文的長度,等等,它們之間用一個回車換行符號(CRLF)分隔。
            請求頭和請求正文之間是一個空行(只有CRLF符號的行),這個行非常重要,它表示請求頭已經結束,接下來的是請求的正文。一些介紹Internet編程的書籍把這個CRLF視為HTTP請求的第四個組成部分。
            在前面的HTTP請求中,請求的正文只有一行內容。當然,在實際應用中,HTTP請求正文可以包含更多的內容。
            1.2 HTTP應答
            和HTTP請求相似,HTTP應答也由三個部分構成,分別是:協議-狀態代碼-描述,應答頭,應答正文。下面是一個HTTP應答的例子:
          HTTP/1.1 200 OK
          Date: Tue, 06 Mar 2012 12:32:58 GMT
          Server: Apache/2.2.22 (Win32)
          Last-Modified: Tue, 06 Mar 2012 11:46:06 GMT
          ETag: “b000000008d9e-57-4ba9196947acd”
          Accept-Ranges: bytes
          Content-Length: 87
          Content-Type: text/html

          經過測試,可以使用滴
          //實例一:
          package com.abin.lii.han.socket;

          import java.io.BufferedReader;
          import java.io.BufferedWriter;
          import java.io.IOException;
          import java.io.InputStreamReader;
          import java.io.OutputStreamWriter;
          import java.net.InetAddress;
          import java.net.Socket;
          import java.net.URLEncoder;

          public class SocketGetServletTest {
           public static void main(String[] args) {
             BufferedWriter httpGetWriter = null;
                   BufferedReader httpResponse = null;
                   try {
                       String hostname = "localhost";// 主機,可以是域名,也可以是ip地址
                       int port = 1443;// 端口
                       InetAddress addr = InetAddress.getByName(hostname);
                       // 建立連接
                       Socket socket = new Socket(addr, port);
                       // 創建數據提交數據流
                       httpGetWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "GBK"));
                       // 相對主機的請求地址
                       StringBuffer httpSubmitPath = new StringBuffer("/abin/ImediaRegister?");
          //             StringBuffer httpSubmitPath = new StringBuffer("http://localhost:7200/abin/ImediaRegister?");
                       httpSubmitPath.append(URLEncoder.encode("app", "GBK"));
                       httpSubmitPath.append("=");
                       httpSubmitPath.append(URLEncoder.encode("longcodeimedia", "GBK"));
                       httpSubmitPath.append("&");
                       httpSubmitPath.append(URLEncoder.encode("udid", "GBK"));
                       httpSubmitPath.append("=");
                       httpSubmitPath.append(URLEncoder.encode("123456789", "GBK"));
                       httpSubmitPath.append("&");
                       httpSubmitPath.append(URLEncoder.encode("source", "GBK"));
                       httpSubmitPath.append("=");
                       httpSubmitPath.append(URLEncoder.encode("limei", "GBK"));
                       httpSubmitPath.append("&");
                       httpSubmitPath.append(URLEncoder.encode("returnFormat", "GBK"));
                       httpSubmitPath.append("=");
                       httpSubmitPath.append(URLEncoder.encode("2", "GBK"));
                       httpGetWriter.write("GET " + httpSubmitPath.toString() + " HTTP/1.1\r\n");
                       httpGetWriter.write("Host: localhost:7200\r\n");
                       httpGetWriter.write("UserAgent: IE8.0\r\n");
                       httpGetWriter.write("Connection: Keep-Alive\r\n");
                       httpGetWriter.write("\r\n");
                       httpGetWriter.flush();
                       // 創建web服務器響應的數據流
                       httpResponse = new BufferedReader(new InputStreamReader(socket.getInputStream(), "GBK"));
                       // 讀取每一行的數據.注意大部分端口操作都需要交互數據。
                       String lineStr = "";
                       while ((lineStr = httpResponse.readLine()) != null) {
                           System.out.println(lineStr);
                       }
                   } catch (Exception e) {
                       e.printStackTrace();
                   } finally {
                       try {
                           if (httpGetWriter != null) {
                               httpGetWriter.close();
                           }
                           if (httpResponse != null) {
                               httpResponse.close();
                           }
                       } catch (IOException e) {
                           e.printStackTrace();
                       }
                   }
               }

                 
          }



          //實例二

          package com.abin.lii.han.socket;

          import java.io.BufferedReader;
          import java.io.BufferedWriter;
          import java.io.InputStreamReader;
          import java.io.OutputStreamWriter;
          import java.net.InetAddress;
          import java.net.Socket;

          public class SocketGetServletTest1 {

           public static void main(String[] args) {
            try {
             Socket socket = new Socket(InetAddress.getLocalHost(), 7200);
             BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
             StringBuffer buffer = new StringBuffer();
             buffer.append("GET http://localhost:7200/abin/ImediaRegister?app=2 HTTP/1.1\r\n");
             buffer.append("Host: localhost:7200\r\n");
             buffer.append("UserAgent: IE8.0\r\n");
             buffer.append("Connection: Keep-Alive\r\n");
             // 注,這是關鍵的關鍵,忘了這里讓我搞了半個小時。這里一定要一個回車換行,表示消息頭完,不然服務器會等待
             buffer.append("\r\n");
             writer.write(buffer.toString());
             writer.flush();

             // --輸出服務器傳回的消息的頭信息
             BufferedReader reader=new BufferedReader(new InputStreamReader(socket.getInputStream()));
             String line = null;
             StringBuilder builder=new StringBuilder();
             while((line=reader.readLine())!=null){
              builder.append(line);
             }
             String result=builder.toString();
             System.out.println("result="+result);
            } catch (Exception e) {
             e.printStackTrace();
            }
           }

          }

           

          posted @ 2012-12-31 08:31 abin 閱讀(3223) | 評論 (0)編輯 收藏

               摘要: MyBatis的動態SQL是基于OGNL表達式的,它可以幫助我們方便的在SQL語句中實現某些邏輯。 MyBatis中用于實現動態SQL的元素主要有:   ifchoose(when,otherwise)trimwheresetforeach if就是簡單的條件判斷,利用if語句我們可以實現某些簡單的條件選擇。先來看如下一個例子: Xml代碼   <...  閱讀全文
          posted @ 2012-12-25 13:10 abin 閱讀(18044) | 評論 (2)編輯 收藏

           1.CachedThreadPool

              CachedThreadPool首先會按照需要創建足夠多的線程來執行任務(Task)。隨著程序執行的過程,有的線程執行完了任務,可以被重新循環使用時,才不再創建新的線程來執行任務。我們采用《Thinking In Java》中的例子來分析。

              首先,任務定義如下(實現了Runnable接口,并且復寫了run方法):

          package net.jerryblog.concurrent;
          public class LiftOff implements Runnable{
              protected int countDown = 10; //Default
              private static int taskCount = 0;
              private final int id = taskCount++; 
              public LiftOff() {}
              public LiftOff(int countDown) {
                  this.countDown = countDown;
              }
              public String status() {
                  return "#" + id + "(" +
                      (countDown > 0 ? countDown : "LiftOff!") + ") ";
              }
              @Override
              public void run() {
                  while(countDown-- > 0) {
                      System.out.print(status());
                      Thread.yield();
                  }
                  
              }   
          }

          采用CachedThreadPool方式執行編寫的客戶端程序如下: 


          package net.jerryblog.concurrent;
          import java.util.concurrent.ExecutorService;
          import java.util.concurrent.Executors;
          public class CachedThreadPool {
              public static void main(String[] args) {
                  ExecutorService exec = Executors.newCachedThreadPool();
                  for(int i = 0; i < 10; i++) {
                      exec.execute(new LiftOff());
                  }
                  exec.shutdown();    
              }
          }

          上面的程序中,有10個任務,采用CachedThreadPool模式,exec沒遇到一個LiftOff的對象(Task),就會創建一個線程來處理任務?,F在假設遇到到第4個任務時,之前用于處理第一個任務的線程已經執行完成任務了,那么不會創建新的線程來處理任務,而是使用之前處理第一個任務的線程來處理這第4個任務。接著如果遇到第5個任務時,前面那些任務都還沒有執行完,那么就會又新創建線程來執行第5個任務。否則,使用之前執行完任務的線程來處理新的任務。

          2.FixedThreadPool

               FixedThreadPool模式會使用一個優先固定數目的線程來處理若干數目的任務。規定數目的線程處理所有任務,一旦有線程處理完了任務就會被用來處理新的任務(如果有的話)。這種模式與上面的CachedThreadPool是不同的,CachedThreadPool模式下處理一定數量的任務的線程數目是不確定的。而FixedThreadPool模式下最多 的線程數目是一定的。

              采用FixedThreadPool模式編寫客戶端程序如下:


          package net.jerryblog.concurrent;
          import java.util.concurrent.ExecutorService;
          import java.util.concurrent.Executors;
          public class FixedThreadPool {
              public static void main(String[] args) {
                  //三個線程來執行五個任務
                  ExecutorService exec = Executors.newFixedThreadPool(3);   
                  for(int i = 0; i < 5; i++) {
                      exec.execute(new LiftOff());
                  }
                  exec.shutdown();
              }
          }

          3.SingleThreadExecutor模式

              SingleThreadExecutor模式只會創建一個線程。它和FixedThreadPool比較類似,不過線程數是一個。如果多個任務被提交給SingleThreadExecutor的話,那么這些任務會被保存在一個隊列中,并且會按照任務提交的順序,一個先執行完成再執行另外一個線程。

              SingleThreadExecutor模式可以保證只有一個任務會被執行。這種特點可以被用來處理共享資源的問題而不需要考慮同步的問題。

              SingleThreadExecutor模式編寫的客戶端程序如下: 



          package net.jerryblog.concurrent;
          import java.util.concurrent.ExecutorService;
          import java.util.concurrent.Executors;
          public class SingleThreadExecutor {
              public static void main(String[] args) {
                  ExecutorService exec = Executors.newSingleThreadExecutor();
                  for (int i = 0; i < 2; i++) {
                      exec.execute(new LiftOff());
                  }
              }
          }

          這種模式下執行的結果如下:
          #0(9) #0(8) #0(7) #0(6) #0(5) #0(4) #0(3) #0(2) #0(1) #0(LiftOff!)
          #1(9) #1(8) #1(7) #1(6) #1(5) #1(4) #1(3) #1(2) #1(1) #1(LiftOff!)
          第一個任務執行完了之后才開始執行第二個任務。   




          posted @ 2012-12-19 12:39 abin 閱讀(432) | 評論 (0)編輯 收藏

          1、

          最近在網上閑逛,突然發現Liferay的SVN,里面有非常多可用的樣例代碼,現在分享給大家:

          地址:

          http://svn.liferay.com/repos/public/plugins/trunk/portlets

           

          用戶名/密碼: guest/guest

          http://svn.liferay.com/repos/public/
          posted @ 2012-12-15 20:04 abin 閱讀(334) | 評論 (0)編輯 收藏

           
          1.簡介
          sed是非交互式的編輯器。它不會修改文件,除非使用shell重定向來保存結果。默認情況下,所有的輸出行都被打印到屏幕上。
          sed編輯器逐行處理文件(或輸入),并將結果發送到屏幕。具體過程如下:首先sed把當前正在處理的行保存在一個臨時緩存區中(也稱為模式空間),然后處理臨時緩沖區中的行,完成后把該行發送到屏幕上。sed每處理完一行就將其從臨時緩沖區刪除,然后將下一行讀入,進行處理和顯示。處理完輸入文件的最后一行后,sed便結束運行。sed把每一行都存在臨時緩沖區中,對這個副本進行編輯,所以不會修改原文件。
           
          2.定址
          定址用于決定對哪些行進行編輯。地址的形式可以是數字、正則表達式、或二者的結合。如果沒有指定地址,sed將處理輸入文件的所有行。
           
          地址是一個數字,則表示行號;是“$"符號,則表示最后一行。例如: 

          sed -n '3p' datafile
          只打印第三行

           

           只顯示指定行范圍的文件內容,例如:

          # 只查看文件的第100行到第200行
          sed -n '100,200p' mysql_slow_query.log

           

          地址是逗號分隔的,那么需要處理的地址是這兩行之間的范圍(包括這兩行在內)。范圍可以用數字、正則表達式、或二者的組合表示。例如:

          sed '2,5d' datafile
          #刪除第二到第五行
          sed '/My/,/You/d' datafile
          #刪除包含"My"行到包含"You"行之間的行
          sed '/My/,10d' datafile
          #刪除包含"My"行到第十行的內容

           

           

          3.命令與選項

          sed命令告訴sed如何處理由地址指定的各輸入行,如果沒有指定地址則處理所有的輸入行。

           

          3.1 sed命令

           命令  功能
           a\

           在當前行后添加一行或多行。多行時除最后一行外,每行末尾需用“\”續行

           c\  用此符號后的新文本替換當前行中的文本。多行時除最后一行外,每行末尾需用"\"續行
           i\  在當前行之前插入文本。多行時除最后一行外,每行末尾需用"\"續行
           d  刪除行
           h  把模式空間里的內容復制到暫存緩沖區
           H  把模式空間里的內容追加到暫存緩沖區
           g  把暫存緩沖區里的內容復制到模式空間,覆蓋原有的內容
           G  把暫存緩沖區的內容追加到模式空間里,追加在原有內容的后面
           l  列出非打印字符
           p  打印行
           n  讀入下一輸入行,并從下一條命令而不是第一條命令開始對其的處理
           q  結束或退出sed
           r  從文件中讀取輸入行
           !  對所選行以外的所有行應用命令
           s  用一個字符串替換另一個
           g  在行內進行全局替換
           
           w  將所選的行寫入文件
           x  交換暫存緩沖區與模式空間的內容
           y  將字符替換為另一字符(不能對正則表達式使用y命令)

           

          3.2 sed選項

           選項  功能
           -e  進行多項編輯,即對輸入行應用多條sed命令時使用
           -n  取消默認的輸出
           -f  指定sed腳本的文件名
           
           
          4.退出狀態
          sed不向grep一樣,不管是否找到指定的模式,它的退出狀態都是0。只有當命令存在語法錯誤時,sed的退出狀態才不是0。
          5.正則表達式元字符
           與grep一樣,sed也支持特殊元字符,來進行模式查找、替換。不同的是,sed使用的正則表達式是括在斜杠線"/"之間的模式。
          如果要把正則表達式分隔符"/"改為另一個字符,比如o,只要在這個字符前加一個反斜線,在字符后跟上正則表達式,再跟上這個字符即可。例如:sed -n '\o^Myop' datafile
           
           元字符  功能  示例
           ^  行首定位符  /^my/  匹配所有以my開頭的行
           $  行尾定位符  /my$/  匹配所有以my結尾的行
           .  匹配除換行符以外的單個字符  /m..y/  匹配包含字母m,后跟兩個任意字符,再跟字母y的行
           *  匹配零個或多個前導字符  /my*/  匹配包含字母m,后跟零個或多個y字母的行
           []  匹配指定字符組內的任一字符  /[Mm]y/  匹配包含My或my的行
           [^]  匹配不在指定字符組內的任一字符  /[^Mm]y/  匹配包含y,但y之前的那個字符不是M或m的行
           \(..\)  保存已匹配的字符  1,20s/\(you\)self/\1r/  標記元字符之間的模式,并將其保存為標簽1,之后可以使用\1來引用它。最多可以定義9個標簽,從左邊開始編號,最左邊的是第一個。此例中,對第1到第20行進行處理,you被保存為標簽1,如果發現youself,則替換為your。
           &  保存查找串以便在替換串中引用  s/my/**&**/  符號&代表查找串。my將被替換為**my**
           \<  詞首定位符  /\<my/  匹配包含以my開頭的單詞的行
           \>  詞尾定位符  /my\>/  匹配包含以my結尾的單詞的行
           x\{m\}  連續m個x  /9\{5\}/ 匹配包含連續5個9的行
           x\{m,\}  至少m個x  /9\{5,\}/  匹配包含至少連續5個9的行
           x\{m,n\}  至少m個,但不超過n個x  /9\{5,7\}/  匹配包含連續5到7個9的行
           
          6.范例
           
          6.1 p命令
          命令p用于顯示模式空間的內容。默認情況下,sed把輸入行打印在屏幕上,選項-n用于取消默認的打印操作。當選項-n和命令p同時出現時,sed可打印選定的內容。
           

          sed '/my/p' datafile
          #默認情況下,sed把所有輸入行都打印在標準輸出上。如果某行匹配模式my,p命令將把該行另外打印一遍。


          sed -n '/my/p' datafile
          #選項-n取消sed默認的打印,p命令把匹配模式my的行打印一遍。

           

          6.2 d命令

          命令d用于刪除輸入行。sed先將輸入行從文件復制到模式空間里,然后對該行執行sed命令,最后將模式空間里的內容顯示在屏幕上。如果發出的是命令d,當前模式空間里的輸入行會被刪除,不被顯示。

          sed '$d' datafile
          #刪除最后一行,其余的都被顯示

          sed '/my/d' datafile
          #刪除包含my的行,其余的都被顯示

           

          6.3 s命令

          sed 's/^My/You/g' datafile
          #命令末端的g表示在行內進行全局替換,也就是說如果某行出現多個My,所有的My都被替換為You。

          sed -n '1,20s/My$/You/gp' datafile
          #取消默認輸出,處理1到20行里匹配以My結尾的行,把行內所有的My替換為You,并打印到屏幕上。

            

          sed 's#My#Your#g' datafile
          #緊跟在s命令后的字符就是查找串和替換串之間的分隔符。分隔符默認為正斜杠,但可以改變。無論什么字符(換行符、反斜線除外),只要緊跟s命令,就成了新的串分隔符。

           

          6.4 e選項

          -e是編輯命令,用于sed執行多個編輯任務的情況下。在下一行開始編輯前,所有的編輯動作將應用到模式緩沖區中的行上。

          sed -e '1,10d' -e 's/My/Your/g' datafile

          #選項-e用于進行多重編輯。第一重編輯刪除第1-3行。第二重編輯將出現的所有My替換為Your。因為是逐行進行這兩項編輯(即這兩個命令都在模式空間的當前行上執行),所以編輯命令的順序會影響結果。

           

          6.5 r命令

          r命令是讀命令。sed使用該命令將一個文本文件中的內容加到當前文件的特定位置上。

          sed '/My/r introduce.txt' datafile
          #如果在文件datafile的某一行匹配到模式My,就在該行后讀入文件introduce.txt的內容。如果出現My的行不止一行,則在出現My的各行后都讀入introduce.txt文件的內容。

           
          6.6 w命令

          sed -n '/hrwang/w me.txt' datafile

           

          6.7 a\ 命令

          a\ 命令是追加命令,追加將添加新文本到文件中當前行(即讀入模式緩沖區中的行)的后面。所追加的文本行位于sed命令的下方另起一行。如果要追加的內容超過一行,則每一行都必須以反斜線結束,最后一行除外。最后一行將以引號和文件名結束。

          sed '/^hrwang/a\
          >hrwang and mjfan are husband\
          >and wife'
          datafile
          #如果在datafile文件中發現匹配以hrwang開頭的行,則在該行下面追加hrwang and mjfan are husband and wife

           

          6.8 i\ 命令

          i\ 命令是在當前行的前面插入新的文本。

           

          6.9 c\ 命令

          sed使用該命令將已有文本修改成新的文本。

           

          6.10 n命令

          sed使用該命令獲取輸入文件的下一行,并將其讀入到模式緩沖區中,任何sed命令都將應用到匹配行緊接著的下一行上。

          sed '/hrwang/{n;s/My/Your/;}' datafile

          注:如果需要使用多條命令,或者需要在某個地址范圍內嵌套地址,就必須用花括號將命令括起來,每行只寫一條命令,或這用分號分割同一行中的多條命令。
           
          6.11 y命令
          該命令與UNIX/Linux中的tr命令類似,字符按照一對一的方式從左到右進行轉換。例如,y/abc/ABC/將把所有小寫的a轉換成A,小寫的b轉換成B,小寫的c轉換成C。
           

          sed '1,20y/hrwang12/HRWANG^$/' datafile
          #將1到20行內,所有的小寫hrwang轉換成大寫,將1轉換成^,將2轉換成$。
          #正則表達式元字符對y命令不起作用。與s命令的分隔符一樣,斜線可以被替換成其它的字符。

           

          6.12 q命令

          q命令將導致sed程序退出,不再進行其它的處理。

          sed '/hrwang/{s/hrwang/HRWANG/;q;}' datafile

           

          6.13 h命令和g命令

          #cat datafile

          My name is hrwang.

          Your name is mjfan.

          hrwang is mjfan's husband.

          mjfan is hrwang's wife.

            

          sed -e '/hrwang/h' -e '$G' datafile

          sed -e '/hrwang/H' -e '$G' datafile

          #通過上面兩條命令,你會發現h會把原來暫存緩沖區的內容清除,只保存最近一次執行h時保存進去的模式空間的內容。而H命令則把每次匹配hrwnag的行都追加保存在暫存緩沖區。

          sed -e '/hrwang/H' -e '$g' datafile

          sed -e '/hrwang/H' -e '$G' datafile

          #通過上面兩條命令,你會發現g把暫存緩沖區中的內容替換掉了模式空間中當前行的內容,此處即替換了最后一行。而G命令則把暫存緩沖區的內容追加到了模式空間的當前行后。此處即追加到了末尾。

           

           

          7. sed腳本

          sed腳本就是寫在文件中的一列sed命令。腳本中,要求命令的末尾不能有任何多余的空格或文本。如果在一行中有多個命令,要用分號分隔。執行腳本時,sed先將輸入文件中第一行復制到模式緩沖區,然后對其執行腳本中所有的命令。每一行處理完畢后,sed再復制文件中下一行到模式緩沖區,對其執行腳本中所有命令。使用sed腳本時,不再用引號來確保sed命令不被shell解釋。例如sed腳本script:

          #handle datafile
          3i\
          ~~~~~~~~~~~~~~~~~~~~~
          3,$s/\(hrwang\) is
           \(mjfan\)/\2 is \1/
          $a\
          We will love eachother forever?。?/span>
           

           

           

          #sed -f script datafile
          My name is hrwang
          Your name is mjfan
          ~~~~~~~~~~~~~~~~~~~~~
          mjfan is hrwang's husband.          #啦啦~~~
          mjfan is hrwang'
          s wife.
          We will love eachother forever??!


          posted @ 2012-12-14 17:11 abin 閱讀(382) | 評論 (0)編輯 收藏

          在MYSQL中插入當前時間:

            NOW()函數以`'YYYY-MM-DD HH:MM:SS'返回當前的日期時間,可以直接存到DATETIME字段中。
            CURDATE()以’YYYY-MM-DD’的格式返回今天的日期,可以直接存到DATE字段中。

            CURTIME()以’HH:MM:SS’的格式返回當前的時間,可以直接存到TIME字段中。
            例:insert into tablename (fieldname) values (now())

            now():以'yyyy-mm-dd hh:mm:ss'返回當前的日期時間,可以直接存到datetime字段中。
            curdate():’yyyy-mm-dd’的格式返回今天的日期,可以直接存到date字段中。

             

          //獲取Mysql系統時間   
          select now() as systime  ; 
          select sysdate() as systime  ; 
          select current_date as systime ;
          select current_time as systime ;
          select current_timestamp as systime ;
          select * from abing where to_days(sysdate())=to_days(createtime);   
          select * from abing where to_days(sysdate())=to_days(createtime);   
           select * from abing where str_to_date(now(),'%Y-%m-%d')=str_to_date(createtime,'%Y-%m-%d');  
          自己寫的例子,為了以后忘記了查詢用:
          use abin;
          create table abin1(
          id integer not null auto_increment,
          name varchar(100),
          create_time datetime ,
          update_time datetime ,
          constraint pk_abin1 primary key(id));
          insert into abin1(name,create_time,update_time) values ('abin1',now(),now());
          insert into abin1(name,create_time,update_time) values ('abin1',sysdate(),sysdate());




          posted @ 2012-12-14 14:32 abin 閱讀(485) | 評論 (0)編輯 收藏

          僅列出標題
          共50頁: First 上一頁 18 19 20 21 22 23 24 25 26 下一頁 Last 
          主站蜘蛛池模板: 万年县| 闻喜县| 德惠市| 乳山市| 浠水县| 遂川县| 澄迈县| 东丰县| 泰兴市| 郑州市| 芒康县| 宁武县| 缙云县| 贵港市| 灵台县| 小金县| 绥宁县| 衡阳市| 循化| 铅山县| 安乡县| 宜春市| 昌平区| 民乐县| 稻城县| 如皋市| 洛隆县| 宜春市| 博乐市| 栾川县| 昌吉市| 建始县| 收藏| 怀宁县| 绥阳县| 阿克| 宁武县| 新民市| 宁明县| 资源县| 仪陇县|