Tomcat 7.0.27 Integration with Atomikos 3.7.1

http://www.atomikos.com/Documentation/Tomcat7Integration35

 

Update: Tomcat 7.0.27 Integration with Atomikos 3.7.1

Installation is quite simple and it envolves the following steps:

 

1- Copy "atomikos-integration-extension-3.7.1-20120529.jar" into TOMCAT_HOME/lib folder.

This jar file contains:

  • 'AtomikosLifecycleListener.java'
  • 'EnhancedTomcatAtomikosBeanFactory.java'
  • 'pom.xml'
  • 'patch-README.txt'

Jar file and source code are available and attached to this page: atomikos-integration-extension-3.7.1-20120529.jarand atomikos-integration-extension-3.7.1-patch.zip

 

2- Edit "server.xml"

According to the needs of your application, standard and additional listeners which are available in Tomcat 7.0.27should be added to 'TOMCAT_HOME/conf/server.xml' file. Then right after the last one, add this listener:

<Listener className="com.atomikos.tomcat.AtomikosLifecycleListener" />

 

3- Edit "context.xml"

Then edit the TOMCAT_HOME/conf/context.xml file. At the beginning of the file you should see this line:

<WatchedResource>WEB-INF/web.xml</WatchedResource>

Right after it, add that one:

<Transaction factory="com.atomikos.icatch.jta.UserTransactionFactory" />

"com.atomikos.tomcat.EnhancedTomcatAtomikosBeanFactory" should be set as factory for both JDBC and JMS connection factory resources. Below, you can see an example of 'context.xml':

<?xml version="1.0" encoding="UTF-8"?>

<!-- The contents of this file will be loaded for each web application -->
<Context>

    <!-- Default set of monitored resources -->
    <WatchedResource>WEB-INF/web.xml</WatchedResource>

  <!-- Atomikos Support for the Tomcat server - register Atomikos as java:comp/UserTransaction -->
  <Transaction factory="com.atomikos.icatch.jta.UserTransactionFactory" />
  <!-- Also register Atomikos TransactionManager as java:comp/env/TransactionManager -->
  <Resource name="TransactionManager"
            auth="Container"
            type="com.atomikos.icatch.jta.UserTransactionManager"
            factory="org.apache.naming.factory.BeanFactory" />

  <!-- Spring LoadTimeWeaver Support for the Tomcat server. -->
  <Loader loaderClass="org.springframework.instrument.classloading.tomcat.TomcatInstrumentableClassLoader"
          useSystemClassLoaderAsParent="false"/>

  <Resource name="jdbc/MyDb"
            auth="Container"
            type="com.atomikos.jdbc.AtomikosDataSourceBean"
            factory="com.atomikos.tomcat.EnhancedTomcatAtomikosBeanFactory"
            uniqueResourceName="MyDb_Resource"
            maxPoolSize="8"
            xaDataSourceClassName="org.apache.derby.jdbc.ClientXADataSource"
            xaProperties.databaseName="MyDb"           
            xaProperties.connectionAttributes="serverName=localhost;portNumber=1527;user=USER;password=PASSWORD;create=true"/>

  <Resource name="jms/ConnectionFactory"
            auth="Container"
            type="com.atomikos.jms.AtomikosConnectionFactoryBean"
            factory="com.atomikos.tomcat.EnhancedTomcatAtomikosBeanFactory"
            uniqueResourceName="ConnectionFactory_Resource"
            xaConnectionFactoryClassName="org.apache.activemq.ActiveMQXAConnectionFactory"
            xaProperties.brokerURL="tcp://localhost:61616?daemon=true"/>

</Context>

 

Tomcat 7 Integration with Atomikos 3.5.2+

It is possible to fully integrate the Atomikos transaction manager into Tomcat. Doing it this way makes the transaction manager shared across all web applications exactly like with any full-blown J2EE server.

 

An apparently simpler way of configuring Tomcat6 with TransactionsEssentials is shown in this third-party blog entry:http://blog.vinodsingh.com/2009/12/jta-transactions-with-atomkios-in.html - we have not tested it though...

 

Important note

When the Atomikos transaction manager is installed globally in Tomcat, you now must also install your JDBC driver at the same global location (ie: into the TOMCAT_HOME/lib folder). If you dont do that, you will get a NoClassDefFoundErrors or a ClassNotFoundException or even a ClassCastException during your web application deployment.

This is not a limitation of Atomikos nor of Tomcat but of the J2EE class loading design that both Tomcat and Atomikos must follow.

 

Installation

Installation is quite simple, it just involves copying some JAR files, a property file and editing some Tomcat configuration files.

 

Atomikos Tomcat Lifecycle Class

The LifecycleListener has to be changed since release 3.5.2. The first class which calls UserTransactionManager.init() is the master for UserTransactionManager. It is not the first class which calls new UserTransactionManager(). Only the master closes UserTransactionManager with its close() method. Therefore UserTransactionManager.init() has to be called after the new operator.

Here is the revised source code:

 

Atomikos Lifecycle Listener.java

package com.atomikos.tomcat;

import org.apache.catalina.Lifecycle;
import org.apache.catalina.LifecycleEvent;
import org.apache.catalina.LifecycleListener;

import com.atomikos.icatch.jta.UserTransactionManager;

public class AtomikosLifecycleListener implements LifecycleListener
{

   private UserTransactionManager utm;

   public void lifecycleEvent(LifecycleEvent event)
   {
      try {
         if (Lifecycle.START_EVENT.equals(event.getType())) {
            if (utm == null) {
               utm = new UserTransactionManager();
            }
            utm.init();
         } else if (Lifecycle.AFTER_STOP_EVENT.equals(event.getType())) {
            if (utm != null) {
               utm.close();
            }
         }
      } catch (Exception e) {
      }
   }
}

 

Atomikos Tomcat BeanFactory Class

This JAR contains a single class file that is an enhanced version of Tomcat JNDI's Bean Factory. Here is its source code:

 

Bean Factory.java

package com.atomikos.tomcat;

import java.util.Enumeration;
import java.util.Hashtable;

import javax.naming.Context;
import javax.naming.Name;
import javax.naming.NamingException;
import javax.naming.RefAddr;
import javax.naming.Reference;
import javax.naming.spi.ObjectFactory;

import org.apache.naming.ResourceRef;
import org.apache.naming.factory.Constants;

import com.atomikos.beans.PropertyUtils;
import com.atomikos.jdbc.AtomikosDataSourceBean;

public class BeanFactory implements ObjectFactory
{

   public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable environment) throws NamingException
   {
      if (obj instanceof ResourceRef) {
         try {
            Reference ref = (Reference) obj;
            String beanClassName = ref.getClassName();
            Class beanClass = null;
            ClassLoader tcl = Thread.currentThread().getContextClassLoader();
            if (tcl != null) {
               try {
                  beanClass = tcl.loadClass(beanClassName);
               } catch (ClassNotFoundException e) {
               }
            } else {
               try {
                  beanClass = Class.forName(beanClassName);
               } catch (ClassNotFoundException e) {
                  e.printStackTrace();
               }
            }
            if (beanClass == null) {
               throw new NamingException("Class not found: " + beanClassName);
            }
            if (!AtomikosDataSourceBean.class.isAssignableFrom(beanClass)) {
               throw new NamingException("Class is not a AtomikosDataSourceBean: " + beanClassName);
            }

            AtomikosDataSourceBean bean = (AtomikosDataSourceBean) beanClass.newInstance();

            int i = 0;
            Enumeration en = ref.getAll();
            while (en.hasMoreElements()) {
               RefAddr ra = (RefAddr) en.nextElement();
               String propName = ra.getType();

               if (propName.equals(Constants.FACTORY) || propName.equals("singleton") || propName.equals("description") || propName.equals("scope") || propName.equals("auth")) {
                  continue;
               }

               String value = (String) ra.getContent();

               PropertyUtils.setProperty(bean, propName, value);

               i++;
            }

            bean.init();
            return bean;

         } catch (Exception ex) {
            throw (NamingException) new NamingException("error creating AtomikosDataSourceBean").initCause(ex);
         }

      } else {
         return null;
      }
   }
}

 

Copying TransactionsEssentials libraries

 

  • Drop the following JARs from the Atomikos distribution into the TOMCAT_HOME/lib folder:
    • transactions.jar
    • transactions-api.jar
    • transactions-jta.jar
    • transactions-jdbc.jar
    • atomikos-util.jar.jar
    • jta.jar

You should also copy the transactions-hibernate3.jar and/or transactions-hibernate2.jar at the same location if you're planning to use Hibernate.

 

Copying Atomikos configuration file

 

  • Drop the following properties file into the TOMCAT_HOME/lib folder: jta.properties

 

Edit server.xml

Then edit the TOMCAT_HOME/conf/server.xml file. At the beginning of the file you should see these four lines:

 

  <Listener className="org.apache.catalina.core.AprLifecycleListener" />
  <Listener className="org.apache.catalina.mbeans.ServerLifecycleListener" />
  <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" />
  <Listener className="org.apache.catalina.storeconfig.StoreConfigLifecycleListener"/>

Right after the last one, add this fifth one:

 

 <Listener className="com.atomikos.tomcat.AtomikosLifecycleListener" />

 

Edit context.xml

Then edit the TOMCAT_HOME/conf/context.xml file. At the beginning of the file you should see this line:

 

 <WatchedResource>WEB-INF/web.xml</WatchedResource>

Right after it, add that one:

 

 <Transaction factory="com.atomikos.icatch.jta.UserTransactionFactory" />

 

Example application

Here is a sample application that demonstrates how you can run TransactionsEssentials in a web application after it has been globally installed.

It is a simple blueprint application that shows and updates the content of a single Derby database.

Download the sample application here: dbtest.war

To install it, simply copy the WAR file in Tomcat's webapps folder. You also need to install Derby's JDBC driver inTOMCAT_HOME/lib.

You can then access it via this URL: http://localhost:8080/dbtest/.

 

Notes

  • This demo uses an embedded Derby database. If it doesn't exist a new one is created in TOMCAT_HOME/work or else, the existing one is reused.
  • The transactions logs and debug logs are stored in TOMCAT_HOME/work.
  • You should get logs during Tomcat's startup and shutdown:
    • during startup: INFO: starting Atomikos Transaction Manager 3.3.0
    • during shutdown: INFO: shutting down Atomikos Transaction Manager

 

Using MySQL

The example uses Derby - however it can be configured with MySQL by changing the webapp context similar to this:

 

<?xml version="1.0" encoding="UTF-8"?>
<Context path="/dbtest" docBase="dbtest.war"
reloadable="true" crossContext="true">
<!-- Resource configuration for JDBC datasource-->
<Resource
name="jdbc/myDB"
auth="Container"
type="com.atomikos.jdbc.AtomikosDataSourceBean"
factory="com.atomikos.tomcat.BeanFactory"
uniqueResourceName="jdbc/myDB"
xaDataSourceClassName="com.mysql.jdbc.jdbc2.optional.MysqlXADataSource"
xaProperties.databaseName="test"
xaProperties.serverName="localhost"
xaProperties.port="3306"
xaProperties.user="USER"
xaProperties.password="PASSWORD"
xaProperties.url="jdbc:mysql://localhost:3306/test"
/>
</Context>

Remember to change the parameter values to your specific environment...

 

Using WebSphere MQ

This example shows how to define pooled JMS Queue Connection Factories and Queues for WebSphere MQ. Note that the uniqueResourceName MUST contain the text MQSeries_XA_RMI.

<?xml version="1.0" encoding="UTF-8"?>
<Context path="/dbtest" docBase="dbtest.war"
reloadable="true" crossContext="true">

<Resource 
name="jms/myQCF" 
auth="Container" 
type="com.atomikos.jms.AtomikosConnectionFactoryBean" 
factory="com.atomikos.tomcat.EnhancedTomcatAtomikosBeanFactory" 
uniqueResourceName="myQCF_MQSeries_XA_RMI" 
xaConnectionFactoryClassName="com.ibm.mq.jms.MQXAQueueConnectionFactory" 
xaProperties.queueManager="XXXX" 
xaProperties.hostName="hostname" 
xaProperties.port="1426" 
xaProperties.channel="XXXX" 
maxPoolSize="3" 
minPoolSize="1" />

<Resource name="jms/myQ" 
auth="Container" 
type="com.ibm.mq.jms.MQQueue" 
factory="com.ibm.mq.jms.MQQueueFactory" 
description="JMS Queue for reading messages" 
QU="MYQ.IN" 
CCSID="819" 
persistence="2" />         
</Context>

For this to work, you need an improved version of the Bean Factory described above, which can also handle JMS Connection Factory Beans:

!EnhancedTomcatAtomikosBeanFactory .java

package com.atomikos.tomcat;

import java.util.Enumeration;
import java.util.Hashtable;

import javax.jms.JMSException;
import javax.naming.Context;
import javax.naming.Name;
import javax.naming.NamingException;
import javax.naming.RefAddr;
import javax.naming.Reference;
import javax.naming.spi.ObjectFactory;

import org.apache.naming.ResourceRef;
import org.apache.naming.factory.Constants;

import com.atomikos.beans.PropertyException;
import com.atomikos.beans.PropertyUtils;
import com.atomikos.jdbc.AtomikosDataSourceBean;
import com.atomikos.jdbc.AtomikosSQLException;
import com.atomikos.jms.AtomikosConnectionFactoryBean;

/**
 * enhancement of com.atomikos.tomcat.BeanFactory (see http://www.atomikos.com/Documentation/Tomcat7Integration35)
 */
public class EnhancedTomcatAtomikosBeanFactory implements ObjectFactory
{

   public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable environment) throws NamingException
   {
      if (obj instanceof ResourceRef) { //see http://fogbugz.atomikos.com/default.asp?community.6.2947.0 for a fix for OpenEJB!
         try {
            Reference ref = (Reference) obj;
            String beanClassName = ref.getClassName();
            Class beanClass = null;
            ClassLoader tcl = Thread.currentThread().getContextClassLoader();
            if (tcl != null) {
               try {
                  beanClass = tcl.loadClass(beanClassName);
               } catch (ClassNotFoundException e) {
               }
            } else {
               try {
                  beanClass = Class.forName(beanClassName);
               } catch (ClassNotFoundException e) {
                  e.printStackTrace();
               }
            }
            if (beanClass == null) {
               throw new NamingException("Class not found: " + beanClassName);
            }
            if (AtomikosDataSourceBean.class.isAssignableFrom(beanClass)) {
               return createDataSourceBean(ref, beanClass);
            } else if (AtomikosConnectionFactoryBean.class.isAssignableFrom(beanClass)) {
               return createConnectionFactoryBean(ref, beanClass);
            } else {
               throw new NamingException("Class is neither an AtomikosDataSourceBean nor an AtomikosConnectionFactoryBean: " + beanClassName);
            }

         } catch (Exception ex) {
            throw (NamingException) new NamingException("error creating AtomikosDataSourceBean").initCause(ex);
         }

      } else {
         return null;
      }
   }

   /**
    * create a DataSourceBean for a JMS datasource
    * 
    * @param ref
    * @param beanClass
    * @return
    * @throws InstantiationException
    * @throws IllegalAccessException
    * @throws PropertyException
    * @throws AtomikosSQLException
    * @throws JMSException
    */
   private Object createConnectionFactoryBean(Reference ref, Class beanClass) throws InstantiationException, IllegalAccessException, PropertyException, JMSException
   {
      AtomikosConnectionFactoryBean bean = (AtomikosConnectionFactoryBean) beanClass.newInstance();

      int i = 0;
      Enumeration en = ref.getAll();
      while (en.hasMoreElements()) {
         RefAddr ra = (RefAddr) en.nextElement();
         String propName = ra.getType();

         if (propName.equals(Constants.FACTORY) || propName.equals("singleton") || propName.equals("description") || propName.equals("scope") || propName.equals("auth")) {
            continue;
         }

         String value = (String) ra.getContent();

         PropertyUtils.setProperty(bean, propName, value);

         i++;
      }

      bean.init();
      return bean;
   }

   /**
    * create a DataSourceBean for a JDBC datasource
    * 
    * @param ref
    * @param beanClass
    * @return
    * @throws InstantiationException
    * @throws IllegalAccessException
    * @throws PropertyException
    * @throws AtomikosSQLException
    */
   private Object createDataSourceBean(Reference ref, Class beanClass) throws InstantiationException, IllegalAccessException, PropertyException, AtomikosSQLException
   {
      AtomikosDataSourceBean bean = (AtomikosDataSourceBean) beanClass.newInstance();

      int i = 0;
      Enumeration en = ref.getAll();
      while (en.hasMoreElements()) {
         RefAddr ra = (RefAddr) en.nextElement();
         String propName = ra.getType();

         if (propName.equals(Constants.FACTORY) || propName.equals("singleton") || propName.equals("description") || propName.equals("scope") || propName.equals("auth")) {
            continue;
         }

         String value = (String) ra.getContent();

         PropertyUtils.setProperty(bean, propName, value);

         i++;
      }

      bean.init();
      return bean;
   }
}

 

Copy Atomikos Integration Extension library

Copy atomikos-integration-extension.jar into TOMCAT_HOME/lib folder.

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Atomikos TransactionsEssentials 是一个为Java平台提供增值服务的并且开源类事务管理器,以下是包括在这个开源版本中的一些功能: l 全面崩溃 / 重启恢复 l 兼容标准的SUN公司JTA API l 嵌套事务 l 为XA和非XA提供内置的JDBC适配器 注释:XA:XA协议由Tuxedo首先提出的,并交给X/Open组织,作为资源管理器(数据库)与事务管理器的接口标准。目前,Oracle、Informix、DB2和Sybase等各大数据库厂家都提供对XA的支持。XA协议采用两阶段提交方式来管理分布式事务。XA接口提供资源管理器与事务管理器之间进行通信的标准接口。XA协议包括两套函数,以xa_开头的及以ax_开头的。 以下的函数使事务管理器可以对资源管理器进行的操作: 1)xa_open,xa_close:建立和关闭与资源管理器的连接。 2)xa_start,xa_end:开始和结束一个本地事务。 3)xa_prepare,xa_commit,xa_rollback:预提交、提交和回滚一个本地事务。 4)xa_recover:回滚一个已进行预提交的事务。 5)ax_开头的函数使资源管理器可以动态地在事务管理器中进行注册,并可以对XID(TRANSACTION IDS)进行操作。 6)ax_reg,ax_unreg;允许一个资源管理器在一个TMS(TRANSACTION MANAGER SERVER)中动态注册或撤消注册。 l 内置的JMS适配器XA-capable JMS队列连接器 注释:JMS:jms即Java消息服务(Java Message Service)应用程序接口是一个Java平台中关于面向消息中间件(MOM)的API,用于在两个应用程序之间,或分布式系统中发送消息,进行异步通信。Java消息服务是一个与具体平台无关的API,绝大多数MOM提供商都对JMS提供支持。 l 通过XA API兼容第三方适配器 l 更好的整合您的项目 l 集成Hibernate 如何使用Atomikos TransactionsEssentials Atomikos TransactionsEssentials 是一个可靠的库,可以加入到您的Java应用程序,也就是说为了使用这个产品,您必须添加一些jar文件(包括在dist和lib文件夹下)到您的应用程序或者应用程序服务器。 请注意:Atomikos TransactionsEssentials是一个非常快速的嵌入式事务管理器,这就意味着,您不需要另外启动一个单独的事务管理器进程(不要查找任何的bin文件夹)。相反,您的应用服务器将有它自己的intra-VM事务管理器。 配置需求:至少Java1.5 jdk,并且最少128M的内存 性能优化:尽管这个软件有着很大的优势,但是想要更好的发挥其作用,可以按以下的方法优化: l 更高的内存,意味着更高的吞吐量(每秒的事务数目) l 使连接池尽可能的大 l 一旦你不需要的连接请马上关闭它们。不要把你的应用程序放在缓存里,让内部连接池为你做这些,这将促使更高效的连接使用 l 不要让活动的事务闲置:终止所有情况下的事务,尤其是在异常报错情况下的事务。这将减少数据库的锁定时间,并且最大效率的处理启用的使用。 如果想获取这些细节的更多信息,也要参阅文档说明部分。 值得注意的是,在我们所有的压力测试中,Atomikos TransactionsEssentials比J2EE的web容器更高效的吞吐量。这些测量值包括日志记录的高效的事务状态,同样,在我们所有的测量中,包括XA和non-XA,高效的效率是一样的。 在J2SE中使用Atomikos Transactions Essentials,只需要按以下步骤 将idst和lib中的jar包全部放入的项目中 创建或者自定义你应用的transactions.properties(或者jta.properties)文件(事务管理器的配置),然后将它放入到classpath中,安装文件夹中包涵一个实例文件;在properties文件中注释(#)后面的是默认值,取消一行并且改变默认值。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

码农丁丁

你的认可是我创作最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值