<?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.
-->
<!-- The contents of this file will be loaded for each web application -->
<Context crossContext="true">
<!-- Default set of monitored resources -->
<WatchedResource>WEB-INF/web.xml</WatchedResource>
<ResourceLink name="jdbc/ExampleDB" global="jdbc/ExampleDB" type="javax.sql.DataSource"/>
<!-- Uncomment this to disable session persistence across Tomcat restarts -->
<!--
<Manager pathname="" />
-->
<!-- Uncomment this to enable Comet connection tacking (provides events
on session expiration as well as webapp lifecycle) -->
<!--
<Valve className="org.apache.catalina.valves.CometConnectionManagerValve" />
-->
</Context>
<?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="8005" 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" />
<!-- 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" />
<!--
数据库连接池配置
-->
<Resource name="jdbc/ExampleDB" auth="Container" type="javax.sql.DataSource"
maxActive="100" maxIdle="30" maxWait="10000"
username="APP" password="APP" driverClassName="org.apache.derby.jdbc.ClientDriver"
url="jdbc:derby://localhost:1527/springside-example;create=true"/>
</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="200" minSpareThreads="100" maxIdleTime="60000"/>
<!-- 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
-->
<!-- executor="tomcatThreadPool"
标明此链接使用上面配置的名称为tomcatThreadPool的连接池,无属性共享连接不会生效 -->
<Connector port="8080" protocol="HTTP/1.1" redirectPort="8443"
connectionTimeout="20000"
executor="tomcatThreadPool"
acceptCount="100"
useBodyEncodingForURI="true"
enableLookups="false"
/>
<!-- 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="8009" protocol="AJP/1.3" redirectPort="8443"
connectionTimeout="20000"
executor="tomcatThreadPool"
backlog="100"
useBodyEncodingForURI="true"
enableLookups="false"
/>
<!-- 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 -->
<Engine name="Catalina" defaultHost="localhost" jvmRoute="cluster1">
<!--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">
<!--
配置虚拟目录,例如:http://localhost:8080
-->
<Context path="/" docBase="D:\workspace\code\HBJH\web"></Context>
<!-- 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>
Tomcat6 Support JTA with JOTM
1.place jotm jars into tomcat6/lib
2. create a file named "carol.properties" in tomcat6/lib with following content:
carol.protocols=jrmp
carol.start.jndi=false
carol.start.ns=false
carol.jvm.rmi.local.call=false
carol.jndi.java.naming.factory.url.pkgs=org.apache.naming
3.edit tomcat's server.xml:
<Context ...>
<Transaction factory="org.objectweb.jotm.UserTransactionFactory" jotm.timeout="60"/>
</Context>
4.modify datasource define in server.xml:
<Resource auth="Container" factory="org.objectweb.jndi.DataSourceFactory" driverClassName="com.mysql.jdbc.Driver"...
5.modify spring config:
<bean id="transactionManager" class="org.springframework.transaction.jta.JtaTransactionManager"/>
support JMS Transaction:
<jms:jca-listener-container transaction-manager="transactionManager">
<jms:listener destination="..." ref="..." />
</jms:jca-listener-container>
JOTM发布了2.14,而官网以及网上大部分资料为2.0*
JOTM2.14的Build-Jdk: 1.5.0_10,tomcat6中可以直接使用,无需再自行打包。
如果只是为了在tomcat6中使用UserTransaction,仅需如下设置
tomcat_home/conf中设置context.xml:
<Resource name="jdbc/TEST_DS"
auth="Container"
type="javax.sql.DataSource"
factory="org.objectweb.jotm.datasource.DataSourceFactory"
driverClassName="oracle.jdbc.driver.OracleDriver"
url="jdbc:oracle:thin:@XXX:1521:xxx"
username="xxx" password="xxx" maxActive="20" maxIdle="10"
maxWait="-1" />
<Resource name="UserTransaction"
auth="Container"
type="javax.transaction.UserTransaction" />
<Transaction factory="org.objectweb.jotm.UserTransactionFactory"
jotm.timeout="60" />
在tomcat_home/conf中加入carol.properties
carol.protocols=jrmp
carol.jvm.rmi.local.call=true
carol.start.jndi=false
carol.start.ns=false
carol.jndi.java.naming.factory.url.pkgs=org.apache.naming
在tomcat_home/lib中加入
carol.jar
howl.jar
jotm-core.jar
jotm-datasource.jar
ow2-connector-1.5-spec.jar
ow2-jta-1.1-spec.jar
xapool.jar
调用程式为
Context ctx = new InitialContext();
DataSource ds = (DataSource)
ctx.lookup("java:comp/env/jdbc/TEST_DS");
UserTransaction ut = (UserTransaction)
ctx.lookup("java:comp/UserTransaction");
java.sql.Connection conn = ds.getConnection();
ut.begin();
ut.commit(); or ut.rollback();
程式最小依赖包为
jotm-core.jar
jotm-client.jar
jotm-datasource.jar
ow2-jta-1.1-spec.jar
xapool.jar
在Tomcat中通过JOTM支持JTA
因为需要将项目从IBM WebSphere Application Server移植到Tomcat上开发,所以研究了一下在Tomcat中通过JNDI查找和使用JDBC及JTA的方法。
Tomcat 是Servlet容器,但它也提供了一个JNDI InitialContext实现,因此用户可以像在J2EE应用程序服务器中一样在Tomcat中使用JNDI查找JDBC数据源。不过在事务处理方面,Tomcat本身并不支持JTA(Java Transaction API),所以需要借助其他的方案。
JOTM(Java Open Transaction Manager)是ObjectWeb的一个开源JTA实现,它本身也是开源应用程序服务器JOnAS(Java Open Application Server)的一部分,为其提供JTA支持和分布式事务管理。JOTM同样可以为Tomcat提供JTA支持,以下将对相关的配置进行简单说明,使用的相应版本为:
Tomcat 5.5.x
JOTM 2.0.x
Oracle 9i
1. 配置Tomcat环境
在$TOMCAT_HOME/conf/context.xml文件中添加以下内容:
<Resource name="jdbc/framework" auth="Container"
type="javax.sql.DataSource"
factory="org.objectweb.jndi.DataSourceFactory"
username="user" password="pwd"
driverClassName="oracle.jdbc.driver.OracleDriver"
url="jdbc:oracle:thin:@172.18.136.200:1521:ORADB"
maxActive="30" maxIdle="30"/>
<Transaction factory="org.objectweb.jotm.UserTransactionFactory"
jotm.timeout="60"/>
2. 添加所需的JAR文件
下载JOTM,将以下文件添加到$TOMCAT_HOME/common/lib/:
jotm.jar
jotm_jrmp_stubs.jar
jotm_iiop_stubs.jar
ow_carol.jar
jta-spec1_0_1.jar
jts1_0.jar
objectweb-datasource.jar
xapool.jar
howl.jar
connector-1_5.jar
同时,还需要添加相应数据库的JDBC包,例如Oracle的classes12.jar
3. 配置JOTM
新建一个carol.properties文件,置于$TOMCAT_HOME/common/classes/,文件内容如下:
# JNDI (Protocol Invocation)
carol.protocols=jrmp
# Local RMI Invocation
carol.jvm.rmi.local.call=true
# do not use CAROL JNDI wrapper
carol.start.jndi=false
# do not start a name server
carol.start.ns=false
# Naming Factory
carol.jndi.java.naming.factory.url.pkgs=org.apache.naming
这样JOTM将不会使用CAROL JNDI wrapper,从而可以避免类装载错误的发生
4. 说明
4.1 JOTM目前的版本在JDK1.5或以上可能无法正常运行,解决的方法有两个:使用JDK1.5重新编译carol库,或者将Tomcat运行在JDK1.4中
4.2 <Transaction>是Tomcat 5中的新标记,对于不支持此标记的老版本,需要使用以下语句代替事务资源的声明:
<!-- Resource configuration for UserTransaction
use JOTM
-->
<Resource name="UserTransaction" auth="Container"
type="javax.transaction.UserTransaction"
factory = "org.objectweb.jotm.UserTransactionFactory"
jotm.timeout = "60"/>
4.3 需要注意的是,使用<Resource>节点声明的资源默认上下文前缀是"java:comp/env",而使用< Transaction>节点时则是"java:comp"。因此,当使用4.2的方式声明用户事务时,相应的JNDI查找代码也应该改为 UserTransaction ut = (UserTransaction)initCtx.lookup("java:comp/env/UserTransaction");
5. 测试
假设数据库中已经做了相应配置,可以使用如下jsp页面进行测试:
<!--test.jsp-->
<%@page contentType="text/html;charset=GB2312"%>
<%@page import="java.sql.*"%>
<%@page import="javax.sql.*"%>
<%@page import="javax.naming.*"%>
<%@page import="javax.transaction.UserTransaction"%>
<%
ResultSet rs = null;
Statement stmt = null;
UserTransaction ut = null;
Connection conn = null;
try {
Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
DataSource ds = (DataSource) envCtx.lookup("jdbc/framework");
ut = (UserTransaction)initCtx.lookup("java:comp/UserTransaction");
conn = ds.getConnection();
ut.begin();
System.out.println("<<< beginning the transaction >>>");
stmt = conn.createStatement(
// ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE
);
rs = stmt.executeQuery("SELECT PRICE FROM TM_PRODUCT WHERE ID=1");
rs.next();
} catch(Exception e) {e.printStackTrace();}
%>
<html>
<body>
Original price:
<%=rs.getString("price")%>
<br>After update:
<%
PreparedStatement pstmt = conn.prepareStatement("update tm_product set price=? where id=1");
pstmt.setInt(1,101);
pstmt.executeUpdate();
rs = stmt.executeQuery("SELECT PRICE FROM TM_PRODUCT WHERE ID=1");
rs.next();
%>
<%=rs.getString("price")%>
<br>After Rollback:
<%
System.out.println("<<< rolling back the transaction >>>");
ut.rollback();//Or ut.commit();
rs = stmt.executeQuery("SELECT PRICE FROM TM_PRODUCT WHERE ID=1");
rs.next();
%>
<%=rs.getString("price")%>
<%conn.close();%>
</body>
</html>
为tomcat分配内存
这里要分配的是允许java使用的最大内存大小,要根据MAS服务器实际配置而定。建议配置如下:
1G内存:JAVA_OPTS='-Xms512m -Xmx512m'
2G内存:JAVA_OPTS='-Xms512m -Xmx1024m'
4G内存:JAVA_OPTS='-Xms512m -Xmx2048m'
用vi打开/opt/tomcat/bin/catalina.sh,在开头加入:
JAVA_OPTS='-Xms512m -Xmx512m'
保存退出。
Tomcat默认可以使用的内存为128MB,在较大型的应用项目中,这点内存是不够的,轻微时,会使系统性能急剧下降,严重时,将导致系统无法运行,影响系统的稳定性。当内存不够用时,常见的问题就是报tomcat内存益处错误,从儿导致客户端包500错误的,如下:解决方法主要是加大TOMCAT可利用内存,并在程序当中加大内存使用。因此根据应用的需求,有必要调整JVM使用内存的大小。现在将手工修改tomcat内存的方法及注意事项列出,希望能对新人有所帮助。
tomcat提供了两种安装模式,即免安装(*.zip)和安装(*.exe)方式。针对不同的安装方式下修改tomcat内存大小的方法几注意问题(windows环境):
方式1:当选择安装方式时,可以在安装tomcat的过程进行设置tomcat初始化内存的大小。但是假如说在安装时没有选择,或者应用改变了,需要增加tomcat内存时怎么半呢?此时,我们就要手工修改tomcat的一些文件了:
看了很多网上的资料,都是说修改<CATALINA_HOME>\bin\catalina.bat文件的内容,即在里面增加一行代码:
set JAVA_OPTS=-Xms512m -Xmx512m //表示初始化最小可用内存和最大可用内存都是512MB(修改相应值即可)
如在catalina.bat的
rem ----- Execute The Requested Command
echo Using CATALINA_BASE: %CATALINA_BASE%
echo Using CATALINA_HOME: %CATALINA_HOME%
echo Using CATALINA_TMPDIR: %CATALINA_TMPDIR%
echo Using JAVA_HOME: %JAVA_HOME%
这一栏改为
rem ----- Execute The Requested Command
set JAVA_OPTS=-Xms512m -Xmx512m
echo Using CATALINA_BASE: %CATALINA_BASE%
echo Using CATALINA_HOME: %CATALINA_HOME%
echo Using CATALINA_TMPDIR: %CATALINA_TMPDIR%
echo Using JAVA_HOME: %JAVA_HOME%
就可以将JAVA虚拟机分配内存 508.0625MB的!
但是很多人修改后,发现修改并没有起作用,即通过windows的服务启动tomcat时,实际的内存还是默认的,修改的设置并没有起作用;而通过<CATALINA_HOME>\bin\startup.bat 启动却是生效的。这是为什么呢?因为在安装过程中,JVM的初始化参数已经写在注册表中了,由于没有修改注册表中相关参数,所以以windows服务方式启动时,修改的并没有生效。而通过<CATALINA_HOME>\bin\startup.bat 启动直接是通过<CATALINA_HOME>\bin\catalina.bat文件中的配置的。你需要重新加载到系统服务中才生效,或者你手工在注册表中查找修改启动值,加载到服务中的时候参数已经配置好了,自己修改artup.bat不会改变注册表中的参数设置。
解决方法:修改注册表中的参数,加入JVM初始化内存的参数:
HKEY_LOCAL_MACHINE\SOFTWARE\Apache Software Foundation\Tomcat Service Manager\Tomcat5\Parameters\JavaOptions
值为
-Dcatalina.home="C:\ApacheGroup\Tomcat 5.0"
-Djava.endorsed.dirs="C:\ApacheGroup\Tomcat 5.0\common\endorsed"
-Xrs
如加入 -Xms512m -Xmx800m
方式2:针对免安装的用户,也可以通过将tomcat注册为windows的一个服务的方式来实现:‘
我们可以对service.bat文件做一些其他修改,使tomcat更加能满足我们各种不同需求时的要求
1. 如果让tomcat编译jsp文件,就在PR_CLASSPATH中加入J2SDK的tools.jar
修改前:
set PR_CLASSPATH=%CATALINA_HOME%\bin\bootstrap.jar
修改后:
set PR_CLASSPATH=%JAVA_HOME%\lib\tools.jar;%CATALINA_HOME%\bin\bootstrap.jar
2.要使用一个特定的JVM,就要修改jvm的参数;要使注册的windows服务的启动方式为自动,增加--Startup Automatic,这个是比较常用的;要用定制的server.xml配置文件并且传递多个参数给StartClass,要修改StartParams的值,各个值之间用分号分隔:
修改前:
"%EXECUTABLE%" //IS//%SERVICE_NAME% --Jvm auto
--StartClass org.apache.catalina.startup.Bootstrap --StopClass org.apache.catalina.startup.Bootstrap
--StartParams start --StopParams stop
修改后:
"%EXECUTABLE%" //IS//%SERVICE_NAME% --Jvm "%JAVA_HOME%\jre\bin\server\jvm.dll"
--StartClass org.apache.catalina.startup.Bootstrap --StopClass org.apache.catalina.startup.Bootstrap
--StartParams "-config;%CUSTOM_SERVERXML_FILE%;-nonaming;start" --StopParams stop
--Startup Automatic
3. 指定最大和最小的内存限制,要增加jvm的初始参数
修改前:
"%EXECUTABLE%" //US//%SERVICE_NAME% --JvmOptions
"-Dcatalina.base=%CATALINA_BASE%;-Dcatalina.home=%CATALINA_HOME%;-Djava.endorsed.dirs=%CATALINA_HOME%\common\endorsed"
--StartMode jvm --StopMode jvm
修改后:
"%EXECUTABLE%" //US//%SERVICE_NAME% --JvmOptions
"-Xms128M;-Xmx256M;-Dcatalina.base=%CATALINA_BASE%;-Dcatalina.home=%CATALINA_HOME%;-Djava.endorsed.dirs=%CATALINA_HOME%\common\endorsed"
--StartMode jvm --StopMode jvm
4.有时注册windows服务成功后,但是启动服务时显示“发生服务特定错误: 0.”
就是因为jvm没有指定,修改Jvm auto为Jvm "%JAVA_HOME%\jre\bin\server\jvm.dll"后重新注册windows服务就可以启动了。
java -server -Xms512m -Xmx512m -XX:MaxNewSize=256m