少年阿宾

那些青春的岁月

  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 阅读(480) | 评论 (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 阅读(594) | 评论 (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 阅读(611) | 评论 (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 阅读(2354) | 评论 (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 阅读(3214) | 评论 (0)编辑 收藏

     摘要: MyBatis的动态SQL是基于OGNL表达式的,它可以帮助我们方便的在SQL语句中实现某些逻辑。 MyBatis中用于实现动态SQL的元素主要有:   ifchoose(when,otherwise)trimwheresetforeach if就是简单的条件判断,利用if语句我们可以实现某些简单的条件选择。先来看如下一个例子: Xml代码   <...  阅读全文
posted @ 2012-12-25 13:10 abin 阅读(18034) | 评论 (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),就会创建一个线程来处理任务。现在假设遇到到第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 阅读(424) | 评论 (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 阅读(330) | 评论 (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!!
 

 

 

#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 阅读(370) | 评论 (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 阅读(473) | 评论 (0)编辑 收藏

仅列出标题
共50页: First 上一页 18 19 20 21 22 23 24 25 26 下一页 Last