码迷,mamicode.com
首页 > 其他好文 > 详细

Tomcat的使用

时间:2018-06-08 15:47:32      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:tomcat

编程语言:
硬件级:微码编程,汇编语言
系统级:C,C++,...
应用级:Java, PHP, Python, Ruby, Perl, C#, ...
Python: PVM
Standard Library
Web Framework:Django, Flask, ...
Java:JVM,JDK
bash:bash explainer
...

程序:指令+数据
    过程式编程:以指令为中心,数据服务于代码;
    对象式编程:以数据为中心,指令服务于数据;
        对象,方法(method)

Java:
    Sun, Green Project, Oak,  James Gosling;
    1995:Java 1.0, Write once, Run Anywhere;
    1996:JDK(Java Development Kit),包含类库(API)、开发工具(javac)、JVM(SUN Classic VM)  
        JDK 1.0,  Applet, AWT
    1997:JDK 1.1
    1998: JDK  1.2
        Sun分拆Java技术为三个方向:
            J2SE:Standard Edition
            J2EE:Enterprise Edition
            J2ME:Mobile Edition

        代表性技术:EJB,java plugin, Swing, JIT(Just In Time,即时编译)

    2000:JDK 1.3
        HotSpot VM
    2002:JDK 1.4

    2006:Sun开源了Java技术,GPL,建立一个称为OpenJDK组织;
        Java 2 SE, Java 2 EE, Java 2 ME

    2011:JDK 1.7
    2014:JDK 1.8
    2016:JDK 1.9

Java代码的运行:
    *.java(source code) --> javac --> *.class(bytecode)
        jvm:class loader,加载程序的类文件,及程序的类文件依赖到的其它的类文件而后运行; 整个运行表现为一个jvm进程;
            threads;

java技术体系:
    Java编程语言
    Java Class文件格式
    Java API 
    Java VM 
        class loader
        执行引擎

    JVM运行时区域:
        方法区:线程共享; 用于存储被JVM加载的class信息、常量、静态变量、方法等;
        堆:是jvm所管理的内存中占用空间最大的一部分;也是GC管理的主要区域;存储对象;
        Java栈:线程私有,存储 线程自己的局部变量;
        PC寄存器:线程私有的内存空间,程序的指令指针;
        本地方法栈:  

安装JDK
    了解当前的java环境:
         ~]# java  -version

    OpenJDK: 
        java-VERSION-openjdk:
            The OpenJDK runtime environment.
        java-VERSION-openjdk-headless:
             The OpenJDK runtime environment without audio and video support.
        java-VERSION-openjdk-devel:
            The OpenJDK development tools.

        CentOS 7:
            VERSION:1.6.0, 1.7.0, 1.8.0
            yum install java-1.8.0-openjdk-devel    安装jdk
        注意:多版本并存时,可使用 alternatives命令设定默认使用的版本;在base源中有
        yum list all|grep openjdk:查看openjdk
    Oracle JDK:
        安装相应版本的rpm包;
            jdk-VERSION-OS-ARCH.rpm
            例如:jdk-1.8.0_25-linux-x64.rpm(到官网下载) 
            rpm -ivh jdk-1.8.0_25-linux-x64.rpm
        注意:安装完成后,要配置JAVA_HOME环境变量,指向java的安装路径;
            OpenJDK:
                JAVA_HOME=/usr
            Oracle JDK:
                JAVA_HOME=/usr/java/jdk_VERSION

vim /etc/profile.d/java.sh
export JAVA_HOME=/usr/java/latest
export PATH=$JAVA_HOME/bin:$PATH
source /etc/profile.d/java.sh 使得配置生效

Java 2 EE:
    CGI: Common Gateway Interface

    Servlet:
        类库;web app;
        Servlet container, Servlet Engine

    JSP: Java Server Page
        类库:
        <html>
            <title>TITLE</title>
            <body>
                <h1>...</h1>
                <%
                    ... java code...
                %>
            </body>
        </html>

        .jsp -->jasper--> .java --> javac --> .class --> jvm 

        注意:基于jasper将静态输出的数据转为java代码进行输出,结果为servlet规范的代码;

    JSP Container:
        JSP + Servlet Container

        Java Web Server:JWS
        ASF:JServ

            O‘Reilly

            Tomcat 3.x
            Tomcat 4.x
                Catalina

            http://tomcat.apache.org/

        商业实现:
            WebSphere, WebLogic, Oc4j, Glassfish, Geronimo, JOnAS, JBoss, ...
        开源实现:
            Tomcat, Jetty, Resin, ...

        Tomcat: Java 2 EE技术体系的不完整实现; 

    安装Tomcat:
        Base Repo:
            tomcat, tomcat-lib, tomcat-admin-webapps, tomcat-webapps, tomcat-docs-      

webapp
yum install tomcat tomcat-lib tomcat-admin-webapps tomcat-webapps tomcat-docs-
webapp 安装tomcat
https://tomcat.apache.org 官方下载地址
Tomcat binary release:
wget http://mirrors.hust.edu.cn/apache/tomcat/tomcat-8/v8.5.31/bin/apache-
tomcat-8.5.31.tar.gz;
tar xf apache-tomcat-VERSION.tar.gz -C /usr/local/
cd /usr/local
ln -sv apache-tomcat-VERSION tomcat
useradd -r tomcat -s /sbin/nologin
chown -R tomcat:tomcat /usr/local/tomcat/*
su - tomcat
tomcat需要运行在jvm虚拟机上,但是jvm也要启动,这就需要自举了
/etc/profile.d/tomcat.sh
export CATALINA_BASE=/usr/local/tomcat
export PATH=$CATALINA_BASE/bin:$PATH
tomcat程序环境:

    tomcat的目录结构
        bin:脚本,及启动时用到的类;
        conf:配置文件目录;
        lib:库文件,Java类库,jar;
        logs:日志文件目录;
        temp:临时文件目录;
        webapps:webapp的默认目录;
        work:工作目录,存放编译后的字节码文件;

    实验:实现manager-gui界面的管理

cd /etc/tomcat/
vim tomcat-users.xml
<user username="tomcat" password="123789" roles="manager-gui"/>
<role rolename="manager-gui"/>
systemctl restart tomcat 重启
在访问默认页面时可以点击Manager-App进行服务程序的控制

catalina.sh --help

        debug             Start Catalina in a debugger
        debug -security   Debug Catalina with a security manager
        jpda start        Start Catalina under JPDA debugger
        run               Start Catalina in the current window
        run -security     Start in the current window with security manager
        start             Start Catalina in a separate window
        start  -security   Start in a separate window with security manager
        stop              Stop Catalina, waiting up to 5 seconds for the process to end
        stop n            Stop Catalina, waiting up to n seconds for the process to end
        stop -force       Stop Catalina, wait up to 5 seconds and then use kill -KILL if still running
        stop n -force     Stop Catalina, wait up to n seconds and then use kill -KILL if still running
        configtest        Run a basic syntax check on server.xml - check exit code for result
        version           What version of tomcat are you running?               

    rpm包安装的程序环境:
        配置文件目录:/etc/tomcat
            主配置文件:server.xml 
        webapps存放位置:/var/lib/tomcat/webapps/
            examples
            manager
            host-manager
            docs
        Unit File:tomcat.service
        环境配置文件:/etc/sysconfig/tomcat

Tomcat:
    使用java语言编写:

    tomcat的配置文件构成:
        server.xml:主配置文件;
        web.xml:每个webapp只有“部署”后才能被访问,它的部署方式通常由web.xml进行定义,其存放位置为WEB-INF/目录中;此文件为所有的webapps提供默认部署相关的配置;
        context.xml:每个webapp都可以使用的配置文件,它通常由专用的配置文件context.xml来定义,其存放位置为WEB-INF/目录中;此文件为所有的webapps提供默认配置;
        tomcat-users.xml:用户认证的账号和密码文件;角色(role),用户(User);此文件在tomcat启动时被装入内存;
        catalina.policy:当使用-security选项启动tomcat时,用于为tomcat设置安全策略; 
        catalina.properties:Java属性的定义文件,用于设定类加载器路径,以及一些与JVM调优相关参数;
        logging.properties:日志系统相关的配置;   

    Tomcat的核心组件:server.xml
        <Server>
            <Service>
                <connector/>
                <connector/>
                ...
                <Engine>
                    <Host>
                        <Context/>
                        <Context/>
                        ...
                    </Host>
                    <Host>
                        ...
                    </Host>
                    ...
                </Engine>
            </Service>
        </Server>

        每一个组件都由一个Java“类”实现,这些组件大体可分为以下几个类型:
            顶级组件:Server
            服务类组件:Service
            连接器组件:http, https, ajp(apache jserv protocol)
            容器类:Engine, Host, Context
            被嵌套类:valve, logger, realm, loader, manager, ...

valve:过滤
realm:认证
集群类组件:listener, cluster, ...

    JSP WebAPP的组织结构:
        /: webapps的根目录
            index.jsp, index.html:主页;
            ...
            WEB-INF/:当前webapp的私有资源路径;通常用于存储当前webapp的web.xml和context.xml配置文件;
            META-INF/:类似于WEB-INF/;
            classes/:类文件,当前webapp所提供的类;
            lib/:类文件,当前webapp所提供的类,被打包为jar格式;

            DocumentRooot /webdata/htdocs/
                /images/

                http://www.ilinux.io/images/

    webapp归档格式:
        .war:webapp; 
        .jar:EJB的类打包文件(类库);
        .rar:资源适配器类打包文件;
        .ear:企业级webapp;
        ...

部署(deploy)webapp的相关操作:
    deploy:将webapp的源文件放置于目标目录(网页程序文件存放目录),配置tomcat服务器能够基于web.xml和context.xml文件中定义的路径来访问此webapp;将其特有的类和依赖的类通过class loader装载至JVM;
        部署有两种方式:
            自动部署:auto deploy
            手动部署:
                冷部署:把webapp复制到指定的位置,而后才启动tomcat;
                热部署:在不停止tomcat的前提下进行部署;
                    部署工具:manager、ant脚本、tcd(tomcat client deployer)等;                    
    undeploy:拆除(反部署),停止webapp,并从tomcat实例上卸载webapp;
    start:启动处于停止状态的webapp;
    stop:停止webapp,不再向用户提供服务;其类依然在jvm上;
    redeploy:重新部署;
    例子:

vim tomcat-users.xml 编辑用户授权文件,授权管理界面给tomcat用户
<role rolename="admin-gui"/>
<user username="tomcat" password="123789" roles="manager-gui,admin-gui"/>
<role rolename="manager-gui"/>
http://172.18.62.61:8080/ 访问地址
点击Manager App按钮,输入用户名和密码,进入资源部署管理界面
在管理界面进行如下配置:
Context Path (required): /myapps
WAR or Directory URL: /data/webapps/test
点击deploy按钮进行发布
点击 Host Manager按钮,配置虚拟主机
Name: localhost.localdomain
App base: /data/webapps
将 /data/webapps下的目录改名为ROOT
curl http://localhost.localdomain:8080/ 进行访问

手动提供一测试类应用,并冷部署:
    # mkidr  -pv  /usr/local/tomcat/webapps/test/{classes,lib,WEB-INF}
    创建文件/usr/local/tomcat/webapps/test/index.jsp 
        <%@ page language="java" %>
        <%@ page import="java.util.*" %>
        <html>
            <head>
                <title>Test Page</title>
            </head>
            <body>
                <% out.println("hello world");
                %>
            </body>
        </html>     

tomcat的两个管理应用:
    manager
    host-manager

tomcat的常用组件配置:

    Server:代表tomcat instance,即表现出的一个java进程;监听在8005端口,只接收“SHUTDOWN”。各server监听的端口不能相同,因此,在同一物理主机启动多个实例时,需要修改其监听端口为不同的端口; 
        port="-1",  #禁用此端口,防止他人用SHUTDOWN指令意外关闭(telnet连接时)
        shutdown="RANDOM_CHARCTER"
    Catalina:是tomcat代码的名称;
    Service:用于实现将一个或多个connector组件关联至一个engine组件;

    Connector组件:
        负责接收请求,常见的有三类http/https/ajp;

        进入tomcat的请求可分为两类:
            (1) standalone : 请求来自于客户端浏览器;
            (2) 由其它的web server反代:来自前端的反代服务器;
                nginx --> http connector --> tomcat 
                httpd(proxy_http_module) --> http connector --> tomcat
                httpd(proxy_ajp_module) --> ajp connector --> tomcat    此是httpd内置模块
                httpd(mod_jk) --> ajp connector --> tomcat  mod_jk是早先外置的模块
                ajp是二进制传输的,比较高效
        属性:
            port="8080" 
            protocol="HTTP/1.1"
            connectionTimeout="20000"   单位为毫秒

            address:监听的IP地址;默认为本机所有可用地址;
            maxThreads:最大并发连接数,默认为200;
            enableLookups:是否启用DNS查询功能;
            acceptCount:等待队列的最大长度;  访问超出最大并发连接数就等待
            secure:
            sslProtocol:    建议使用tls1.2以上的版本

    Engine组件:Servlet实例,即servlet引擎,其内部可以一个或多个host组件来定义站点; 通常需要通过defaultHost来定义默认的虚拟主机;

        属性:
            name=
            defaultHost="localhost"
            jvmRoute=

    Host组件:位于engine内部用于接收请求并进行相应处理的主机或虚拟主机,示例:
         <Host name="localhost"  appBase="webapps"
            unpackWARs="true" autoDeploy="true">
        </Host>

        常用属性说明:
            (1) appBase:此Host的webapps的默认存放目录,指存放非归档的web应用程序的目录或归档的WAR文件目录路径;可以使用基于$CATALINA_BASE变量所定义的路径的相对路径;
            (2) autoDeploy:在Tomcat处于运行状态时,将某webapp放置于appBase所定义的目录中时,是否自动将其部署至tomcat;

            示例:
              <Host name="tc1.magedu.com" appBase="/appdata/webapps" unpackWARs="true" autoDeploy="true">
            </Host>

            # mkdir -pv /appdata/webapps
            # mkdir -pv /appdata/webapps/ROOT/{lib,classes,WEB-INF}
            提供一个测试页即可;

    Context组件:
        示例:
            <Context path="/PATH" docBase="/PATH/TO/SOMEDIR" reloadable=""/>

    综合示例:
        <Host name="node1.magedu.com" appBase="/web/apps" unpackWARs="true" autoDeploy="true">
            <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
                prefix="node1_access" suffix=".log"
                pattern="%h %l %u %t &quot;%r&quot; %s %b" />
            <Context path="/test" docBase="test" reloadable=""> #当test不在默认目录下

· 时进行访问;
<Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
prefix="node1_testaccess" suffix=".log"
pattern="%h %l %u %t "%r" %s %b" />
</Context>
</Host>

    Valve组件:
        <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
            prefix="localhost_access_log" suffix=".txt"
            pattern="%h %l %u %t &quot;%r&quot; %s %b" />

        Valve存在多种类型:
            定义访问日志:org.apache.catalina.valves.AccessLogValve
            定义访问控制:org.apache.catalina.valves.RemoteAddrValve 

             <Valve className="org.apache.catalina.valves.RemoteAddrValve" deny="172\.16\.100\.67"/>

实验:nginx作为反向代理,对动态页面转给tomcat,静态页面则自己解析,响应给客户端
nginx和tomcat在一台主机上
yum install nginx
cd /etc/nginx/
vim nginx.conf
root /data/webapps/ROOT; 公共资源,静态与动态都有;
index index.jsp index.html
location ~* .(jsp|do)$ {
proxy_pass http://server1.localhost:8080;
}
nginx 启动服务
测试:
http://172.18.62.61/index.jsp
http://172.18.62.61/

LNMT:Linux Nginx MySQL Tomcat 
    Client (http) --> nginx (reverse proxy)(http) --> tomcat  (http connector)

    location / {
        proxy_pass http://tc1.magedu.com:8080;
    }

    location ~* \.(jsp|do)$ {
        proxy_pass http://tc1.magedu.com:8080;
    }

LAMT:Linux Apache(httpd) MySQL Tomcat 
    httpd的代理模块:
        proxy_module
        proxy_http_module:适配http协议客户端;
        proxy_ajp_module:适配ajp协议客户端;

    Client (http) --> httpd (proxy_http_module)(http) --> tomcat  (http connector)
    Client (http) --> httpd (proxy_ajp_module)(ajp) --> tomcat  (ajp connector)
    Client (http) --> httpd (mod_jk)(ajp) --> tomcat  (ajp connector)

    proxy_http_module代理配置示例:    只实现了动态内容的调度
        <VirtualHost *:80>
            ServerName      tc1.magedu.com
            ProxyRequests Off   关闭正向代理,以使用反向代理
            ProxyVia        On  添加代理首部
            ProxyPreserveHost On    保留代理主机的域名地址
            <Proxy *>
                Require all granted
            </Proxy>
            ProxyPass / http://tc1.magedu.com:8080/
            ProxyPa***everse / http://tc1.magedu.com:8080/ 
            <Location />
                Require all granted
            </Location>
        </VirtualHost>

        location /test/ {
            proxy_pass http://172.16.0.76:8080/;
        }   #nginx的配置

    proxy_ajp_module代理配置示例:
        <VirtualHost *:80>
            ServerName      tc1.magedu.com
            ProxyRequests Off
            ProxyVia        On
            ProxyPreserveHost On
            <Proxy *>
                Require all granted
            </Proxy>
                ProxyPass / ajp://tc1.magedu.com:8009/ 
                ProxyPa***everse / ajp://tc1.magedu.com:8009/ 
            <Location />
                Require all granted
            </Location>
        </VirtualHost>

    /data/webapps/eshop
        eshop-1.1
        eshop-1.2
        eshop-1.3
        eshop-1.4
    在 /data/webapps目录下降各个版本放进去,然后用eshop做为软链接指向要发布的版本

课外实践:
    client --> nginx --> httpd --> tomcat
    proxy_http_module)(http) --> tomcat  (http connector)
    Client (http) --> httpd (proxy_ajp_module)(ajp) --> tomcat  (ajp connector)

课外练习:
    根据文档,部署javaee-bbs或solo;

mysql是通过mysql协议进行通调用的,可以通过mysql客户端软件进行调用mysql的API接口;程
序员也可以通过加载类库直接调用函数访问mysql的API接口;
tomcat是java的,java程序连接数据库要用到一个封装好类库的客户端库专门连接mysql服务器,
可以到mysql官网进行下载,下载好直接放到/usr/share/java/tomcat下即可,在程序运行时需要
mysql连接时自动调用;但是这里不用,自带的有
mysql连接器下载官网:https://dev.mysql.com/downloads/connector/

回顾:

jsp: java server page 
Java 2 SE --> Java 2 EE
    Tomcat:JDK + Servlet, JSP

server.xml:
    <server>
        <service>
            <connector />
            ...
            <Engine>
                <Host>
                    <Context/>
                    ...
                </Host>
                ...
            </Engine>
        </service>
    </server>

Tomcat处理的请求:
    nt:nginx->http->tomcat(http connector)
    at:httpd->http->tomcat(http connector)
        httpd->ajp->tomcat(ajp connector)

    nat, hat

会话保持:
    (1) session sticky
        source_ip
            nginx: ip_hash
            haproxy: source
            lvs: sh
        cookie:
            nginx:hash 
            haproxy: cookie
    (2) session cluster:delta session manager
    (3) session server:redis(store), memcached(cache)

Tomcat Cluster(session)
    (1) session sticky
    (2) session cluster
        tomcat delta manager
    (3) session server 
        memcached

Tomcat Cluster
    (1) httpd + tomcat cluster
        httpd: mod_proxy, mod_proxy_http, mod_proxy_balancer
        tomcat cluster:http connector
    (2) httpd + tomcat cluster
        httpd: mod_proxy, mod_proxy_ajp, mod_proxy_balancer
        tomcat cluster:ajp connector
    (3) httpd + tomcat cluster
        httpd: mod_jk
        tomcat cluster:ajp connector
    (4) nginx + tomcat cluster

    第一种方法的实现:   即httpd调度,效率低
        <proxy balancer://tcsrvs>
            BalancerMember http://172.18.100.67:8080
            BalancerMember http://172.18.100.68:8080
            ProxySet lbmethod=byrequests
        </Proxy>

        <VirtualHost *:80>
            ServerName lb.magedu.com
            ProxyVia On
            ProxyRequests Off
            ProxyPreserveHost On
            <Proxy *>
                Require all granted
            </Proxy>
            ProxyPass / balancer://tcsrvs/
            ProxyPa***everse / balancer://tcsrvs/
            <Location />
                Require all granted
            </Location>
        </VirtualHost>  

    BalancerMember:
        BalancerMember [balancerurl] url [key=value [key=value ...]]
            status:
                D: Worker is disabled and will not accept any requests.
                S: Worker is administratively stopped.
                I: Worker is in ignore-errors mode and will always be considered available.
                H: Worker is in hot-standby mode and will only be used if no other viable workers are available.    如sorry页面
                E: Worker is in an error state.
                N: Worker is in drain mode and will only accept existing sticky sessions destined for itself and ignore all other requests.
            loadfactor:
                负载因子,即权重;
            lbmethod:
                Balancer load-balance method. Select the load-balancing scheduler method to use. Either byrequests, to perform weighted request counting; bytraffic, to perform weighted traffic byte count balancing; or bybusyness, to perform pending request balancing. The default is byrequests.
            stickysession
                Balancer sticky session name. The value is usually set to something like JSESSIONID or PHPSESSIONID, and it depends on the backend application server that support sessions. If the backend application server uses different name for cookies and url encoded id (like servlet containers) use | to separate them. The first part is for the cookie the second for the path.
                Available in Apache HTTP Server 2.4.4 and later.

    会话粘性的实现方法:
        Header add Set-Cookie "ROUTEID=.%{BALANCER_WORKER_ROUTE}e; path=/" env=BALANCER_ROUTE_CHANGED

        <proxy balancer://tcsrvs>   #注意TomcatA就是上面ROUTEID的值
            BalancerMember http://172.18.100.67:8080 route=TomcatA loadfactor=1
            BalancerMember http://172.18.100.68:8080 route=TomcatB loadfactor=2
            ProxySet lbmethod=byrequests
            ProxySet stickysession=ROUTEID
        </Proxy>

        <VirtualHost *:80>
            ServerName lb.magedu.com
            ProxyVia On
            ProxyRequests Off
            ProxyPreserveHost On
            <Proxy *>
                Require all granted
            </Proxy>
            ProxyPass / balancer://tcsrvs/
            ProxyPa***everse / balancer://tcsrvs/
            <Location />
                Require all granted
            </Location>
        </VirtualHost>  

        启用管理接口:
            <Location /balancer-manager>
                SetHandler balancer-manager
                ProxyPass !
                Require all granted
            </Location>             
            http://172.18.62.63/balancer-manager    浏览器访问管理接口界面
            示例程序:
                演示效果,在TomcatA上某context中(如/test),提供如下页面
                <%@ page language="java" %>
                <html>
                    <head><title>TomcatA</title></head>
                    <body>
                        <h1><font color="red">TomcatA.magedu.com</font></h1>
                        <table align="centre" border="1">
                            <tr>
                                <td>Session ID</td>
                            <% session.setAttribute("magedu.com","magedu.com"); %>
                                <td><%= session.getId() %></td>
                            </tr>
                            <tr>
                                <td>Created on</td>

Tomcat的使用

标签:tomcat

原文地址:http://blog.51cto.com/angwoyufengtian/2126387

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!