??xml version="1.0" encoding="utf-8" standalone="yes"?>久久看片网站,五月天激情综合网,五月天精品一区二区三区http://www.aygfsteel.com/hk2000c/category/27378.html技术源于哲学,哲学来源于生z? 兛_生活Q关注健P兛_他h zh-cnSat, 17 Nov 2007 19:02:56 GMTSat, 17 Nov 2007 19:02:56 GMT60Mapping a Blob to a byte[]http://www.aygfsteel.com/hk2000c/archive/2007/11/16/161085.htmlhk2000chk2000cFri, 16 Nov 2007 09:46:00 GMThttp://www.aygfsteel.com/hk2000c/archive/2007/11/16/161085.htmlhttp://www.aygfsteel.com/hk2000c/comments/161085.htmlhttp://www.aygfsteel.com/hk2000c/archive/2007/11/16/161085.html#Feedback0http://www.aygfsteel.com/hk2000c/comments/commentRss/161085.htmlhttp://www.aygfsteel.com/hk2000c/services/trackbacks/161085.htmlHibernate 1.2.3 has built-in support for blobs. Hibernate natively maps blob columns to java.sql.Blob. However, it's sometimes useful to read the whole blob into memory and deal with it as a byte array.

One approach for doing this to create a new UserType as follows.

package mypackage;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.sql.Blob;
import cirrus.hibernate.Hibernate;
import cirrus.hibernate.HibernateException;
import cirrus.hibernate.UserType;
public class BinaryBlobType implements UserType
{
public int[] sqlTypes()
{
return new int[] { Types.BLOB };
}
public Class returnedClass()
{
return byte[].class;
}
public boolean equals(Object x, Object y)
{
return (x == y)
|| (x != null
&& y != null
&& java.util.Arrays.equals((byte[]) x, (byte[]) y));
}
public Object nullSafeGet(ResultSet rs, String[] names, Object owner)
throws HibernateException, SQLException
{
Blob blob = rs.getBlob(names[0]);
return blob.getBytes(1, (int) blob.length());
}
public void nullSafeSet(PreparedStatement st, Object value, int index)
throws HibernateException, SQLException
{
st.setBlob(index, Hibernate.createBlob((byte[]) value));
}
public Object deepCopy(Object value)
{
if (value == null) return null;
byte[] bytes = (byte[]) value;
byte[] result = new byte[bytes.length];
System.arraycopy(bytes, 0, result, 0, bytes.length);
return result;
}
public boolean isMutable()
{
return true;
}
}

The BinaryBlobType will convert a blob into a byte array and back again.

Here's how to use it. First, define an entity that contains a byte[] property:

public class ImageValue
{
private long id;
private image byte[];
public long getId() { return id; }
public void setId(long id) { this.id = id; }
public byte[] getImage() { return image; }
public void setImage(byte[] image) { this.image = image; }
}

Then map a blob column onto the byte[] property:

<class name="ImageValue" table="IMAGE_VALUE">
<id name="id/>
<property name="image" column="IMAGE" type="mypackage.BinaryBlobType"/>
</class>

Notes:

1) Blobs aren't cachable. By converting the blob into a byte array, you can now cache the entity.

2) This approach reads the whole blob into memory at once.

3) The above type is known to work for reading blobs out of the db. Other usage patterns might also work.

Comments (GK)

I changed isMutable() to return true, since an array is a mutable object.

The use of setBlob() will work on some drivers, but not all. I think its more portable to use setBytes() or even setBinaryStream().

comments (db)

db's comment above was right, setBlob() didn't work on Oracle, I used setBytes().

comments (Chad Woolley)

Below is a modified nullsafeset() that i needed to use to get it to work with tomcat 4.1.27 & oracle 8/9i - the normal calls don't work through the tomcat/dbcp connection pool wrapper objects... (this caused me great pain)

pls note that the setBytes() doesn't seem to work with oracle driver & hibernate

d.birch@eclipsegroup.com.au

public void nullSafeSet(PreparedStatement st, Object value, int index)
throws HibernateException, SQLException
{
if(st instanceof org.apache.commons.dbcp.DelegatingPreparedStatement &&
((org.apache.commons.dbcp.DelegatingPreparedStatement)st).getDelegate()
instanceof oracle.jdbc.OraclePreparedStatement)
{
oracle.sql.BLOB blob = oracle.sql.BLOB.createTemporary(
((org.apache.commons.dbcp.PoolableConnection)st.getConnection()).getDelegate(), false, oracle.sql.BLOB.DURATION_SESSION);
blob.open(BLOB.MODE_READWRITE);
OutputStream out = blob.getBinaryOutputStream();
try
{
out.write((byte[])value);
out.flush();
out.close();
}
catch(IOException e)
{
throw new SQLException("failed write to blob" + e.getMessage());
}
blob.close();
((oracle.jdbc.OraclePreparedStatement)((org.apache.commons.dbcp.DelegatingPreparedStatement)st).getDelegate()).setBLOB(index, blob);
}
else
{
st.setBlob(index, Hibernate.createBlob((byte[]) value));
}
}
//and.. note the null check, oracle drivers return a null blob...
public Object nullSafeGet(ResultSet rs, String[] names, Object owner)
throws HibernateException, SQLException
{
final Blob blob = rs.getBlob(names[0]);
return blob != null?blob.getBytes(1, (int)blob.length()):null;
}

/ comments Vanitha

I had to use the user type to save pdfs as oraBLOBs in oracle 91 database. nullsafeSet

needed a sligh modification , or else ther was a classcastexception. Used oracle Blob instead of Hibernate Blob type and it works.

 public void nullSafeSet(PreparedStatement st, Object value, int index)
throws HibernateException, SQLException
{
oracle.sql.BLOB t_blob = oracle.sql.BLOB.createTemporary(((org.jboss.resource.adapter.jdbc.WrappedConnection) st.getConnection()).getUnderlyingConnection(),
false, oracle.sql.BLOB.DURATION_SESSION);
OutputStream t_out = null;
t_blob.open(BLOB.MODE_READWRITE);
t_out = t_blob.getBinaryOutputStream();
try
{
t_out.write((byte[]) value);
t_out.flush();
t_out.close();
}
catch (IOException e)
{
throw new SQLException("failed write to blob" + e.getMessage());
}
t_blob.close();
st.setBlob(index, t_blob);
}

</code>



hk2000c 2007-11-16 17:46 发表评论
]]>
spring调用Oracle存储q程,q返回结果集的完整实?http://www.aygfsteel.com/hk2000c/archive/2007/11/16/161082.htmlhk2000chk2000cFri, 16 Nov 2007 09:31:00 GMThttp://www.aygfsteel.com/hk2000c/archive/2007/11/16/161082.htmlhttp://www.aygfsteel.com/hk2000c/comments/161082.htmlhttp://www.aygfsteel.com/hk2000c/archive/2007/11/16/161082.html#Feedback0http://www.aygfsteel.com/hk2000c/comments/commentRss/161082.htmlhttp://www.aygfsteel.com/hk2000c/services/trackbacks/161082.htmlq是ȝ以前使用spring调用Oracle存储q程Qƈ用cursorq回l果集的一个完整实例,希望能对大家有帮助?

1. 创徏表:

代码
  1. create table TEST_USERS    
  2. (    
  3.   USER_ID  VARCHAR2(10) not null,    
  4.   NAME     VARCHAR2(10) not null,    
  5.   PASSWORD VARCHAR2(20) not null    
  6. )  

 

2. 创徏存储q程Q?

代码
  1. create or replace package display_users_package is    
  2.      type search_results is ref cursor;    
  3.      procedure display_users_proc(results_out out search_results, userId in test_users.user_id%type);    
  4. end display_users_package;    
  5.   
  6. create or replace package body display_users_package is    
  7.      procedure display_users_proc(results_out out search_results, userId in test_users.user_id%type)    
  8.           is    
  9.           begin    
  10.           if userId is not null then    
  11.               open results_out for select * from test_users where user_id like userId || '%';    
  12.           else    
  13.               open results_out for  select * from test_users;    
  14.           end if;    
  15.       end display_users_proc;    
  16. end display_users_package;  

 

q个results_out是一个游标类型,用来q回查找的结果集?/p>

3. 完整实现代码Q?

代码
  1. import java.sql.CallableStatement;   
  2. import java.sql.Connection;   
  3. import java.sql.ResultSet;   
  4. import java.sql.SQLException;   
  5. import java.util.ArrayList;   
  6. import java.util.HashMap;   
  7. import java.util.List;   
  8. import java.util.Map;   
  9.   
  10. import javax.sql.DataSource;   
  11.   
  12. import oracle.jdbc.OracleTypes;   
  13.   
  14. import org.springframework.dao.DataAccessException;   
  15. import org.springframework.jdbc.core.CallableStatementCallback;   
  16. import org.springframework.jdbc.core.CallableStatementCreator;   
  17. import org.springframework.jdbc.core.JdbcTemplate;   
  18.   
  19. import com.spring.stored.procedure.util.DataContextUtil;   
  20.   
  21. /**  
  22.  * @author Jane Jiao  
  23.  *  
  24.  */  
  25. public class SpringStoredProce {   
  26.        
  27.     public List<Map> execute(String storedProc, String params){   
  28.         List<Map> resultList = null;   
  29.         try{   
  30.             final DataSource ds = DataContextUtil.getInstance().getDataSource();   
  31.             final JdbcTemplate template = new JdbcTemplate(ds);   
  32.             resultList = (List<Map>)template.execute(new ProcCallableStatementCreator(storedProc, params),   
  33.                                                      new ProcCallableStatementCallback());   
  34.         }catch(DataAccessException e){   
  35.             throw new RuntimeException("execute method error : DataAccessException " + e.getMessage());   
  36.         }   
  37.          return resultList;   
  38.     }   
  39.        
  40.        
  41.     /**  
  42.      * Create a callable statement in this connection.  
  43.      */  
  44.     private class ProcCallableStatementCreator implements CallableStatementCreator {   
  45.         private String storedProc;   
  46.         private String params;   
  47.            
  48.        
  49.         /**  
  50.          * Constructs a callable statement.  
  51.          * @param storedProc                  The stored procedure's name.  
  52.          * @param params                      Input parameters.  
  53.          * @param outResultCount              count of output result set.  
  54.          */  
  55.         public ProcCallableStatementCreator(String storedProc, String params) {   
  56.             this.params = params;   
  57.             this.storedProc = storedProc;   
  58.         }   
  59.            
  60.         /**  
  61.          * Returns a callable statement  
  62.          * @param conn          Connection to use to create statement  
  63.          * @return cs           A callable statement  
  64.          */  
  65.         public CallableStatement createCallableStatement(Connection conn) {   
  66.             StringBuffer storedProcName = new StringBuffer("call ");   
  67.             storedProcName.append(storedProc + "(");   
  68.             //set output parameters   
  69.             storedProcName.append("?");   
  70.             storedProcName.append(", ");   
  71.                
  72.             //set input parameters   
  73.             storedProcName.append("?");   
  74.             storedProcName.append(")");   
  75.   
  76.             CallableStatement cs = null;   
  77.             try {   
  78.                 // set the first parameter is OracleTyep.CURSOR for oracel stored procedure   
  79.                 cs = conn.prepareCall(storedProcName.toString());   
  80.                 cs.registerOutParameter (1, OracleTypes.CURSOR);   
  81.                // set the sencond paramter   
  82.                 cs.setObject(2, params);   
  83.             } catch (SQLException e) {   
  84.                 throw new RuntimeException("createCallableStatement method Error : SQLException " + e.getMessage());   
  85.             }   
  86.             return cs;   
  87.         }   
  88.            
  89.     }   
  90.        
  91.     /**  
  92.      *   
  93.      * The ProcCallableStatementCallback return a result object,   
  94.      * for example a collection of domain objects.  
  95.      *  
  96.      */  
  97.     private class ProcCallableStatementCallback implements CallableStatementCallback {   
  98.            
  99.         /**  
  100.          * Constructs a ProcCallableStatementCallback.  
  101.          */  
  102.         public ProcCallableStatementCallback() {   
  103.         }   
  104.   
  105.         /**  
  106.          * Returns a List(Map) collection.  
  107.          * @param cs                       object that can create a CallableStatement given a Connection  
  108.          * @return resultsList             a result object returned by the action, or null  
  109.          */  
  110.         public Object doInCallableStatement(CallableStatement cs){   
  111.             List<Map> resultsMap =  new ArrayList<Map>();   
  112.             try {   
  113.                 cs.execute();    
  114.                 ResultSet rs = (ResultSet) cs.getObject(1);   
  115.                 while (rs.next()) {   
  116.                     Map<String, String> rowMap = new HashMap<String, String>();   
  117.                     rowMap.put("userId", rs.getString("USER_ID"));   
  118.                     rowMap.put("name", rs.getString("NAME"));   
  119.                     rowMap.put("password", rs.getString("PASSWORD"));   
  120.                     resultsMap.add(rowMap);   
  121.                 }      
  122.                 rs.close();   
  123.             }catch(SQLException e) {   
  124.                 throw new RuntimeException("doInCallableStatement method error : SQLException " + e.getMessage());   
  125.             }   
  126.             return resultsMap;   
  127.        }   
  128.     }   
  129. }   

 

4. 试代码Q在q里使用了Junit4试Q?

代码
  1. import static org.junit.Assert.assertNotNull;    
  2. import static org.junit.Assert.assertTrue;    
  3.   
  4. import java.util.List;    
  5. import java.util.Map;    
  6.   
  7. import org.junit.After;    
  8. import org.junit.Before;    
  9. import org.junit.Test;    
  10.   
  11. /**   
  12.  * @author Jane Jiao   
  13.  *   
  14.  */    
  15. public class SpringStoredProceTest {    
  16.        
  17.    private SpringStoredProce springStoredProce;    
  18.   
  19.    /**   
  20.     * @throws java.lang.Exception   
  21.     */    
  22.    @Before    
  23.    public void setUp() throws Exception {    
  24.       springStoredProce = new SpringStoredProce();    
  25.    }    
  26.   
  27.    /**   
  28.     * @throws java.lang.Exception   
  29.     */    
  30.    @After    
  31.    public void tearDown() throws Exception {    
  32.       springStoredProce = null;    
  33.    }    
  34.   
  35.    /**   
  36.     * Test method for {@link com.hactl.listingframework.dao.SpringStoredProce#execute(java.lang.String, java.lang.String)}.   
  37.     */    
  38.    @Test    
  39.    public void testExecute() {    
  40.       final String storedProcName = "display_users_package.display_users_proc";    
  41.       final String param = "test";    
  42.       List<Map> resultList = springStoredProce.execute(storedProcName, param);    
  43.       assertNotNull(resultList);    
  44.       assertTrue(resultList.size() > 0);    
  45.       for (int i = 0; i < resultList.size(); i++) {    
  46.          Map rowMap = resultList.get(i);    
  47.          final String userId = rowMap.get("userId").toString();    
  48.          final String name = rowMap.get("name").toString();    
  49.          final String password = rowMap.get("password").toString();    
  50.          System.out.println("USER_ID=" + userId + "\t name=" + name + "\t password=" + password);    
  51.       }    
  52.           
  53.    }    
  54. }  

 

5. 试的输出结果:

代码
  1. USER_ID=test1    name=aa    password=aa    
  2. USER_ID=test2    name=bb    password=bb    
  3. USER_ID=test3    name=cc    password=cc  


hk2000c 2007-11-16 17:31 发表评论
]]>
ActiveMQ 实践之\(? ActiveMQ 4.x +JBoss 4.x MDP实战?http://www.aygfsteel.com/hk2000c/archive/2007/11/16/161072.htmlhk2000chk2000cFri, 16 Nov 2007 09:10:00 GMThttp://www.aygfsteel.com/hk2000c/archive/2007/11/16/161072.htmlhttp://www.aygfsteel.com/hk2000c/comments/161072.htmlhttp://www.aygfsteel.com/hk2000c/archive/2007/11/16/161072.html#Feedback0http://www.aygfsteel.com/hk2000c/comments/commentRss/161072.htmlhttp://www.aygfsteel.com/hk2000c/services/trackbacks/161072.html关键?   ActiveMQ    

ActiveMQ 实践之\(? ActiveMQ 4.x +JBoss 4.x MDP实战?/font>

      ?lt;<ActiveMQ 实践之\(? ActiveMQ 4.x +JBoss 4.x 整合?/a> >>里面我们比较详细的讲解了ActiveMQ与JBoss的整?
既然选择了JBoss,那么目里面或多或少都会使用到EJB,下面我们pl地介绍如何在ActiveMQ 4.x+JBOSS 4.x环境下开?br /> Message Driven Bean,q且与用jbossMQ在配|上作了比较详细地比较。这里的OrderMessage 仅仅是一个自动生成的Message Driven Bean,在onMessageҎ里面,作日志输入?/p>

 一. 配置ejb-jar.xml
      
        1.  ejb-jar.xml 不能使用XML DTD,需要?font color="#ff0000">XML Schema(XSD)
            
很多朋友可能使用XDoclet来生成ejb-jar.xml,我这里直接用XDoclet生成的ejb-jar.xml?/font>

<!--CTYPE ejb-jar PUBLIC "-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 2.0//EN" "http://java.sun.com/dtd/ejb-jar_2_0.dt-->

           但是在ActiveMQ+JBoss配置中间需要用新的XML Schema才能完成对ra的定?如下.

xml 代码
  1. <ejb-jar xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/ejb-jar_2_1.xsd" version="2.1">  

 

2. ejb-jar.xml 直接使用JBossMQ的Message DriverBean 和用ActiveMQ RA配置的区?/font>

        (1) .使用JBossMQ的MessageDrivenBean?ejb-jar.xml配置

xml 代码
  1. <!-- Message Driven Beans -->  
  2. <message-driven>  
  3.     <description>  
  4.           
  5.     description>  
  6.     <display-name>Name for OrderMessagedisplay-name>  
  7.     <ejb-name>OrderMessageejb-name>  
  8.     <ejb-class>com.mostone.ejb.OrderMessageejb-class>  
  9.     <transaction-type>Containertransaction-type>  
  10.     <acknowledge-mode>Auto-acknowledgeacknowledge-mode>  
  11.     <message-driven-destination>  
  12.         <destination-type>javax.jms.Queuedestination-type>  
  13.     message-driven-destination>  
  14. message-driven>  

     (2). 使用ActiveMQ RA配置的MessageDrivenBean?font color="#ff0000">ejb-jar.xml配置

xml 代码
  1. <!-- Message Driven Beans -->  
  2. <message-driven>  
  3.     <description>  
  4.           
  5.     description>  
  6.     <display-name>Name for OrderMessagedisplay-name>  
  7.     <ejb-name>OrderMessageejb-name>  
  8.     <ejb-class>com.mostone.ejb.OrderMessageejb-class>  
  9.     <transaction-type>Containertransaction-type>  
  10.     <acknowledge-mode>Auto-acknowledgeacknowledge-mode>  
  11.     <!--使用了activetion-config-->  
  12.     <activation-config>  
  13.         <activation-config-property>  
  14.             <activation-config-property-name>destinationactivation-config-property-name>  
  15.             <activation-config-property-value>queue.outboundactivation-config-property-value>  
  16.         activation-config-property>  
  17.         <activation-config-property>  
  18.             <activation-config-property-name>destinationTypeactivation-config-property-name>  
  19.             <activation-config-property-value>javax.jms.Queueactivation-config-property-value>  
  20.         activation-config-property>  
  21.     activation-config>  
  22. message-driven>  

        其中destination,destinationType是ra.xml里面提供的配|属?(q里官方的文档是Destination,DestinationType, 而实际上activemq-ra.rar里面的ra.xml是destination,destinationTypeQ注意大写区别)

?font face="Arial">. 配置jboss.xml
           大部分配|都是在jboss.xml里面.
         1.使用JBossMQ 和用ActiveMQ RA配置Message Driven Bean的区?br />            1.) 使用JBossMQ 的配|?/font>


xml 代码
  1. <message-driven>  
  2.     <ejb-name>OrderMessageejb-name>  
  3.     <destination-jndi-name>queue/testQueuedestination-jndi-name>  
  4. message-driven>  

         2.) 使用ActiveMQ RA的配|?/p>

xml 代码
  1. <message-driven>  
  2.     <ejb-name>ActiveMQMDPejb-name>  
  3.     <!-- 使用了resource-adapter-name -->  
  4.     <resource-adapter-name>activemq-ra.rarresource-adapter-name>  
  5.     <!-- q里的configuration-name 需要和后面container-name 的名字相?nbsp;-->  
  6.     <configuration-name>ActiveMQ Message Driven Beanconfiguration-name>  
  7. message-driven>  

        2. jboss.xml 配置invoker proxy和container 支持ActiveMQ RA

xml 代码
  1. <invoker-proxy-bindings>  
  2.     <invoker-proxy-binding>  
  3.         <name>activemq-message-driven-beanname>  
  4.         <invoker-mbean>defaultinvoker-mbean>  
  5.         <proxy-factory>org.jboss.ejb.plugins.inflow.JBossMessageEndpointFactoryproxy-factory>  
  6.         <proxy-factory-config>  
  7.             <endpoint-interceptors>  
  8.                 <interceptor>org.jboss.proxy.ClientMethodInterceptorinterceptor>  
  9.                 <interceptor>org.jboss.ejb.plugins.inflow.MessageEndpointInterceptorinterceptor>  
  10.                 <interceptor>org.jboss.proxy.TransactionInterceptorinterceptor>  
  11.                 <interceptor>org.jboss.invocation.InvokerInterceptorinterceptor>  
  12.             endpoint-interceptors>  
  13.         proxy-factory-config>  
  14.     invoker-proxy-binding>  
  15. invoker-proxy-bindings>  

MessageDrivenBean的container配置,q里?container-name>必须和上面的相同 才能起作?


 

xml 代码
  1. <container-configurations>  
  2.     <container-configuration>  
  3.         <container-name>ActiveMQ Message Driven Beancontainer-name>  
  4.         <call-logging>falsecall-logging>  
  5.         <invoker-proxy-binding-name>activemq-message-driven-beaninvoker-proxy-binding-name>  
  6.         <container-interceptors>  
  7.             <interceptor>org.jboss.ejb.plugins.ProxyFactoryFinderInterceptorinterceptor>  
  8.                 <interceptor>org.jboss.ejb.plugins.LogInterceptorinterceptor>  
  9.                 <interceptor>org.jboss.ejb.plugins.RunAsSecurityInterceptorinterceptor>  
  10.                 <!-- CMT -->  
  11.                 <interceptor transaction="Container">org.jboss.ejb.plugins.TxInterceptorCMTinterceptor>  
  12.                 <interceptor transaction="Container">org.jboss.ejb.plugins.CallValidationInterceptorinterceptor>  
  13.                 <interceptor transaction="Container" metricsEnabled="true">org.jboss.ejb.plugins.MetricsInterceptorinterceptor>  
  14.                 <interceptor transaction="Container">org.jboss.ejb.plugins.MessageDrivenInstanceInterceptorinterceptor>  
  15.                 <!-- BMT -->  
  16.                 <interceptor transaction="Bean">org.jboss.ejb.plugins.MessageDrivenInstanceInterceptorinterceptor>  
  17.                 <interceptor transaction="Bean">org.jboss.ejb.plugins.MessageDrivenTxInterceptorBMTinterceptor>  
  18.                 <interceptor transaction="Bean">org.jboss.ejb.plugins.CallValidationInterceptorinterceptor>  
  19.                 <interceptor transaction="Bean" metricsEnabled="true">org.jboss.ejb.plugins.MetricsInterceptorinterceptor>  
  20.                 <interceptor>org.jboss.resource.connectionmanager.CachedConnectionInterceptorinterceptor>  
  21.         container-interceptors>  
  22.         <instance-pool>org.jboss.ejb.plugins.MessageDrivenInstancePoolinstance-pool>  
  23.         <instance-cache>instance-cache>  
  24.         <persistence-manager>persistence-manager>  
  25.         <container-pool-conf>  
  26.                 <MaximumSize>100MaximumSize>  
  27.         container-pool-conf>  
  28.         container-configuration>  
  29. container-configurations>  

以上是ActiveMQ+JBoss InBound 的配|?/font>

?在Servlet中通过发送消?验证上面的Message Driven Bean

     Z验证q个MessageDrivenBean能够正常工作,我用一个很单的servlet向这个queue发送消?前一的activemq-ds.xml 已经提供在启动的时候绑定了JNDI activemq/QueueConnectionFactory,activemq/queue/outbound,我们直接使用p?

java 代码
  1. try {   
  2.         initialContext = new InitialContext();   
  3.         QueueConnectionFactory connectionFactory = (QueueConnectionFactory) initialContext   
  4.                 .lookup("java:activemq/QueueConnectionFactory");   
  5.            Connection con=connectionFactory.createConnection();   
  6.         Session session =  con.createSession(false, Session.AUTO_ACKNOWLEDGE);   
  7.   
  8.         Queue queue = (Queue) initialContext.lookup("activemq/queue/outbound");   
  9.         MessageProducer producer = session.createProducer(queue);   
  10.         TextMessage txtMessage = session.createTextMessage();   
  11.         txtMessage.setText("A");   
  12.         producer.send(txtMessage);   
  13.         producer.close();   
  14.         session.close();   
  15.         con.close();   
  16.            
  17.     } catch (NamingException e) {   
  18.         // TODO Auto-generated catch block   
  19.         e.printStackTrace();   
  20.     } catch (JMSException e) {   
  21.         // TODO Auto-generated catch block   
  22.         e.printStackTrace();   
  23.     }   

?关于durable方式订阅topic的补充说?br />      使用durable方式,你需要在ejb-jar.xml中额外的配置,subscriptionDurability,clientId,subscriptionName

xml 代码
  1. <activation-config>  
  2.     <activation-config-property>  
  3.         ......   
  4.         <activation-config-property>  
  5.             <activation-config-property-name>subscriptionDurabilityactivation-config-property-name>  
  6.             <activation-config-property-value>Durableactivation-config-property-value>  
  7.         activation-config-property>  
  8.         <activation-config-property>  
  9.             <activation-config-property-name>clientIdactivation-config-property-name>  
  10.             <activation-config-property-value>fooactivation-config-property-value>  
  11.         activation-config-property>  
  12.         <activation-config-property>  
  13.             <activation-config-property-name>subscriptionNameactivation-config-property-name>  
  14.             <activation-config-property-value>baractivation-config-property-value>  
  15.         activation-config-property>  
  16.         ......   
  17.     activation-config-property>  
  18. activation-config>  

 

ok q样可以用durable方式订阅topic了?/p>

参考文?
        
JBoss Integration
       ActiveMQ Inbound Communication
    ActiveMQ Outbound Communication




hk2000c 2007-11-16 17:10 发表评论
]]>
ActiveMQ 实践之\(? ActiveMQ 4.x +JBoss 4.x 整合?http://www.aygfsteel.com/hk2000c/archive/2007/11/16/161071.htmlhk2000chk2000cFri, 16 Nov 2007 09:06:00 GMThttp://www.aygfsteel.com/hk2000c/archive/2007/11/16/161071.htmlhttp://www.aygfsteel.com/hk2000c/comments/161071.htmlhttp://www.aygfsteel.com/hk2000c/archive/2007/11/16/161071.html#Feedback0http://www.aygfsteel.com/hk2000c/comments/commentRss/161071.htmlhttp://www.aygfsteel.com/hk2000c/services/trackbacks/161071.html关键?   ActiveMQ    

      ActiveMQ本n是开源项?所以采用ActiveMQ的项目往往也是以其他开源Y件共同构?目前L开源应用服务器有Boss,geronimo,JOnAsQ而其中geronimo 默认的JMS Provider是ActiveMQQ那我们q重介lActiveMQ与JBoss,JOnAs的整合方?/p>

本文参考了 Integrating Apache ActiveMQ with JBoss?a >JBoss Integration,再根据笔者实际整合经验ȝ而成?/p>

 一.整合需要的环境.
              jdk1.5
              jboss-4.0.5.GA
              activemq-ra-4.1.0-incubator.rar  (在ActiveMQ 4.*  lib\optional 目录里面有对应的ra的压~包)
   开始整合前L保jboss能够正确的启动v来?/font>

             ?整合步骤

              1. 步骤一: 解压activemq-rar-4.1.0-incubator.rar ?jboss-4.0.5.GA\server\default\deploy\activemq-ra.rar (q个是目录名? 下面是activemq-rar.rar目录下面的文件和子目?h意红色标记的地方(后面会逐一说明,整合的过E?

              activeio-core-3.0.0-incubator.jar
              activemq-core-4.1.0-incubator.jar
              activemq-ra-4.1.0-incubator.jar
              backport-util-concurrent-2.1.jar
              commons-logging-1.0.3.jar
              derby-10.1.1.0.jar
              geronimo-j2ee-management_1.0_spec-1.0.jar
              spring-2.0.jar
              spring-1.2.6.jar
              xbean-spring-2.7.jar
              broker-config.xml
              META-INF 
 2.步骤? 删除多余?font color="#ff0000">spring-1.2.6.jar,׃4.1.0的ra里面包含?个不同版本的spring会触发一个exception的?https://issues.apache.org/activemq/browse/AMQ-1124, 而且Z以后能够使用新的spring schema配置方式,我们q里会删?font color="#ff0000">spring-1.2.6.jar
,保留spring-2.0.jar?最新的snapshot version的ra已经L了这个多余的spring-1.2.6.jar).

               3.步骤? 修改META-INF\ra.xml,让JBoss使用broker-config.xml 作ؓ默认的配|文仉|borker. 修改下面的地?br />

  1. <config-property-value>config-property-value>              
  2. <!--  <config-property-value>xbean:broker-config.xml</config-property-value>-->  

      改ؓ:

  1. <!-- <config-property-value></config-property-value> -->  
  2. <config-property-value>xbean:broker-config.xmlconfig-property-value>  

    表示使用broker-config.xml来配|启动ActiveMQ.
 
                 4.步骤? 修改borker-config.xml,默认的borker-config.xml会生一个错?无论是我使用的版本还是最后的snapshot版本,默认的borker-config.xml都会让xbean-spring 2.7(snapshot 使用的是2.8)抛出exception.解决的办法如?/div>
       ?nbsp;       
  1. <beans xmlns="http://activemq.org/config/1.0">  
  2.           <broker useJmx="true" >    
     
     改ؓ
 
  1. <beans>  
  2. <broker useJmx="true" xmlns="http://activemq.org/config/1.0">  
 
   卛_
       
              5.步骤? xbean-spring-2.7.jar (或者是2.8) 复制到jboss-4.0.5.GA\server\default\lib下面
 
          ?使用整合完毕的ActiveMQ作ؓdsl定到JBoss的JNDI服务?/div>
                ~写jboss-4.0.5.GA\server\default\depoly\activemq-ds.xml
xml 代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <!DOCTYPE connection-factories   
  3.     PUBLIC "-//JBoss//DTD JBOSS JCA Config 1.5//EN"   
  4.     "http://www.jboss.org/j2ee/dtd/jboss-ds_1_5.dtd">  
  5.   
  6. <connection-factories>  
  7.    <tx-connection-factory>  
  8.       <jndi-name>activemq/QueueConnectionFactory</jndi-name>  
  9.       <xa-transaction/>  
  10.       <track-connection-by-tx/>  
  11.       <rar-name>activemq-ra.rar</rar-name>  
  12.       <connection-definition>javax.jms.QueueConnectionFactory</connection-definition>  
  13.       <ServerUrl>tcp://localhost:61616</ServerUrl>  
  14.       <min-pool-size>1</min-pool-size>  
  15.       <max-pool-size>200</max-pool-size>  
  16.       <blocking-timeout-millis>30000</blocking-timeout-millis>  
  17.       <idle-timeout-minutes>3</idle-timeout-minutes>  
  18.    </tx-connection-factory>  
  19.   
  20.    <tx-connection-factory>  
  21.       <jndi-name>activemq/TopicConnectionFactory</jndi-name>  
  22.       <xa-transaction/>  
  23.       <track-connection-by-tx/>  
  24.       <rar-name>activemq-ra.rar</rar-name>  
  25.       <connection-definition>javax.jms.TopicConnectionFactory</connection-definition>  
  26.       <ServerUrl>tcp://localhost:61616</ServerUrl>  
  27.       <min-pool-size>1</min-pool-size>  
  28.       <max-pool-size>200</max-pool-size>  
  29.       <blocking-timeout-millis>30000</blocking-timeout-millis>  
  30.       <idle-timeout-minutes>3</idle-timeout-minutes>  
  31.    </tx-connection-factory>  
  32.       
  33.    <mbean code="org.jboss.resource.deployment.AdminObject" name="activemq.queue:name=outboundQueue">  
  34.       <attribute name="JNDIName">activemq/queue/outbound</attribute>  
  35.       <depends optional-attribute-name="RARName">jboss.jca:service=RARDeployment,name=&apos;activemq-ra.rar&apos;</depends>  
  36.       <attribute name="Type">javax.jms.Queue</attribute>  
  37.       <attribute name="Properties">PhysicalName=queue.outbound</attribute>  
  38.    </mbean>  
  39.   
  40.    <mbean code="org.jboss.resource.deployment.AdminObject" name="activemq.topic:name=inboundTopic">  
  41.       <attribute name="JNDIName">activemq/topic/inbound</attribute>  
  42.       <depends optional-attribute-name="RARName">jboss.jca:service=RARDeployment,name=&apos;activemq-ra.rar&apos;</depends>  
  43.       <attribute name="Type">javax.jms.Topic</attribute>  
  44.       <attribute name="Properties">PhysicalName=topic.inbound</attribute>  
  45.    </mbean>  
  46.   
  47. </connection-factories>  
               
               启动JBoss.如果看见以下信息pCActiveMQ已经成功启动,q且使用上面的ds配置文g成功地将topic/queuel定CJNDI服务上?/div>
              ......
              [TransportConnector] Connector tcp://localhost:61616 Started
              [NetworkConnector] Network Connector bridge Started
              [BrokerService] ActiveMQ JMS Message Broker (localhost, ID:MyNoteBook-2165-1173250880171-1:0) started
              ......
              [ConnectionFactoryBindingService] Bound ConnectionManager 'jboss.jca:service=ConnectionFactoryBinding,name=activemq/QueueConnectionFactory' to JNDI name 'java:activemq/QueueConnectionFactory'
              [ConnectionFactoryBindingService] Bound ConnectionManager 'jboss.jca:service=ConnectionFactoryBinding,name=activemq/TopicConnectionFactory' to JNDI name 'java:activemq/TopicConnectionFactory'
                [AdminObject] Bound admin object 'org.apache.activemq.command.ActiveMQQueue' at 'activemq/queue/outbound'
                [AdminObject] Bound admin object 'org.apache.activemq.command.ActiveMQTopic' at 'activemq/topic/inbound
                ......
              
             ?验证ActiveMQ+JBoss
             q里你可以用简单的jms  clientq接到broker-config.xml里面的协议连接器上面,默认的是tcp://localhost:61616
             在后面我们会在此整合基础上开发Message Driver Bean和用spring MDP 2U构?nbsp;来验证本ơActiveMQ+JBoss的整合?/div>


hk2000c 2007-11-16 17:06 发表评论
]]>
ActiveMQ 实践之\(? 使用Queue或者Topic发?接受消息 http://www.aygfsteel.com/hk2000c/archive/2007/11/16/161069.htmlhk2000chk2000cFri, 16 Nov 2007 09:05:00 GMThttp://www.aygfsteel.com/hk2000c/archive/2007/11/16/161069.htmlhttp://www.aygfsteel.com/hk2000c/comments/161069.htmlhttp://www.aygfsteel.com/hk2000c/archive/2007/11/16/161069.html#Feedback0http://www.aygfsteel.com/hk2000c/comments/commentRss/161069.htmlhttp://www.aygfsteel.com/hk2000c/services/trackbacks/161069.html

本篇主要讲解在未使用其他框架(Spring)整合情况?独立ZActiveMQ,使用JMS规范q行消息通信?br />     
     一.JMS回顾
       因ؓActiveMQ是一个JMS Provider的实?因此在开始实作前,有必要复习下JMS的基知识
    Java Message Service (JMS)是sun提出来的为J2EE提供企业消息处理的一套规?JMS目前?套规范还在用JMS 1.0.2b?.1. 1.1已经成ؓL的JMS Provider事实上的标准?
      *1.1主要在session上面有一些重要改?比如支持建立同一session上的transaction,让他支持同时发送P2P(Queue)消息和接?br /> Topic消息?br />       
       在JMS中间主要定义?U消息模式Point-to-Point (点对?,Publich/Subscribe Model (发布/订阅?Q?br />     其中在Publich/Subscribe 模式下又有Nondurable subscription和durable subscription (持久化订?2U消息处理方式?br />     
     下面是JMS规范基本的接口和实现
     JMS Common Interfacse PTP-Specific Interface   Pub/Sub-specific interfaces
     ConnectionFactory     QueueConnectionFactory   TopicConnectionFactory
     Connection            QueueConnection          TopicConnection
     Destination           Queue                    Topic
     Session               QueueSession             TopiSession
     MessageProducer       QueueSender              TopicPublisher
     MessageConsumer       QueueReceiver/QueueBrwer TopicSubscriber


     ?使用Queue

         下面以ActiveMQ example的代码ؓ主进行说?br />         
        1. 使用ActiveMQ的ConnectionQConnectionFactory 建立q接,注意q里没有用到pool
       

java 代码
  1. import org.apache.activemq.ActiveMQConnection   
  2. import org.apache.activemq.ActiveMQConnectionFactory   

        //建立Connection

java 代码
  1. protected Connection createConnection() throws JMSException, Exception {   
  2.      ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(user, pwd, url);   
  3.      Connection connection = connectionFactory.createConnection();   
  4.      if (durable && clientID!=null) {   
  5.          connection.setClientID(clientID);   
  6.      }   
  7.      connection.start();   
  8.      return connection;   
  9.     }  

        //建立Session
  

java 代码
  1. protected Session createSession(Connection connection) throws Exception {   
  2.          Session session = connection.createSession(transacted, ackMode);   
  3.          return session;   
  4.         }   

        2。发送消息的代码
 //建立QueueSession
 

java 代码
  1. protected MessageProducer createProducer(Session session) throws JMSException {   
  2.         Destincation destination = session.createQueue("queue.hello");   
  3.         MessageProducer producer = session.createProducer(destination);   
  4.         producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);   
  5.            
  6.         if( timeToLive!=0 )   
  7.             producer.setTimeToLive(timeToLive);   
  8.         return producer;   
  9.         }   

         //使用Producer发送消息到Queue
    

java 代码
  1. producer.send(message);   

       
        3。接受消?在JMS规范里面,你可以?br />   

java 代码
  1. QueueReceiver/QueueBrowser直接接受消息,但是更多的情况下我们采用消息通知方式,卛_现MessageListener接口   
  2.  public void onMessage(Message message) {   
  3.  //process message   
  4.  }   
  5.           
  6.  //set MessageListner ,receive message   
  7.  Destincation destination = session.createQueue("queue.hello");   
  8.  consumer = session.createConsumer(destination);   
  9.  consumer.setMessageListener(this);   

       
        以上是使用jms queue发送接受消息的基本方式

 
     ?Topic

        1. 建立q接
   

java 代码
  1. protected Connection createConnection() throws JMSException, Exception {      
  2.         ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(user, pwd, url);      
  3.         Connection connection = connectionFactory.createConnection();      
  4.         //如果你要使用DurableSubScription 方式,你必Mؓconnection讄一个ClientID      
  5.         if (durable && clientID!=null) {      
  6.             connection.setClientID(clientID);      
  7.         }      
  8.         connection.start();      
  9.         return connection;      
  10.        }      

       2. 建立Session

java 代码
  1. protected Session createSession(Connection connection) throws Exception {      
  2.         Session session = connection.createSession(transacted, ackMode);      
  3.         return session;      
  4.         }    

 3.创徏Producer 发送消息到Topic   
       

java 代码
  1. //create topic on  session   
  2.        topic = session.createTopic("topic.hello");   
  3.  producer = session.createProducer(topic);   
  4.        //send message    
  5.        producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);   
  6.  producer.send(message);   


 4.创徏Consumer接受消息(基本上和Queue相同)

java 代码
  1. Destincation destination  = session.createTopic("topic.hello");      
  2. MessageConsumer consumer = session.createConsumer(destination);      
  3. consumer.setMessageListener(this);      
  4.            
  5.      //如果你用的是Durable Subscription方式,你必d建立connection的时?nbsp;     
  6.      //讄ClientID,而且建立comsumer的时候用createDurableSubscriberҎ,Z指定一个consumerName?nbsp;     
  7.  //connection.setClientID(clientId);      
  8.  //consumer = session.createDurableSubscriber((Topic) destination, consumerName);   

       
 ?q接ActiveMQ的方?br />         ActiveMQConnectionFactory 提供了多U连接到Broker的方?a title="ActiveMQq接协议" >activemq.apache.org/uri-protocols.html

 常见的有
 vm://host:port     //vm
 tcp://host:port    //tcp
 ssl://host:port    //SSL
 stomp://host:port  //stomp协议可以跨语a,目前有很多种stomp client ?java,c#,c/c++,ruby,python...);



hk2000c 2007-11-16 17:05 发表评论
]]>
ActiveMQ 实践之\(一) 启动你的ActiveMQ http://www.aygfsteel.com/hk2000c/archive/2007/11/16/161070.htmlhk2000chk2000cFri, 16 Nov 2007 09:05:00 GMThttp://www.aygfsteel.com/hk2000c/archive/2007/11/16/161070.htmlhttp://www.aygfsteel.com/hk2000c/comments/161070.htmlhttp://www.aygfsteel.com/hk2000c/archive/2007/11/16/161070.html#Feedback0http://www.aygfsteel.com/hk2000c/comments/commentRss/161070.htmlhttp://www.aygfsteel.com/hk2000c/services/trackbacks/161070.html     E度: 入门


    一.安装ActiveMQ

       首先去http://activemq.apache.org/download.html 下蝲最新版?.1.0release (http://activemq.apache.org/activemq-410-release.html),
    解压apache-activemq-4.1-incubator.zip(或者apache-activemq-4.1-incubator.tar.gz)目录如下:
      
       +bin       (windows下面的bat和unix/linux下面的sh)
       +conf      (activeMQ配置目录,包含最基本的activeMQ配置文g)
       +data      (默认是空?
       +docs      (index,replease版本里面没有文档,-.-b不知道ؓ啥不?
       +example   (几个例子
       +lib       (activemMQ使用到的lib)
       -apache-activemq-4.1-incubator.jar  (ActiveMQ的binary)
       -LICENSE.txt      
       -NOTICE.txt       
       -README.txt
       -user-guide.html


       你可以用bin\activemq.bat(activemq) 启动,如果一切顺?你就会看见类g面的信息
      (l节可能不一?比如路径,或者jmx,jdbc信息)

  ACTIVEMQ_HOME: D:\java\framework_and_lib\activemq\apache-activemq-4.1-incubator\
bin\..
Loading message broker from: xbean:activemq.xml
INFO  BrokerService                  - ActiveMQ null JMS Message Broker (localho
st) is starting
INFO  BrokerService                  - For help or more information please see:
http://incubator.apache.org/activemq/
INFO  ManagementContext              - JMX consoles can connect to service:jmx:r
mi:///jndi/rmi://localhost:1099/jmxrmi
INFO  JDBCPersistenceAdapter         - Database driver recognized: [apache_derby
_embedded_jdbc_driver]
INFO  DefaultDatabaseLocker          - Attempting to acquire the exclusive lock
to become the Master broker
INFO  DefaultDatabaseLocker          - Becoming the master on dataSource: org.ap
ache.derby.jdbc.EmbeddedDataSource@1d840cd
INFO  JournalPersistenceAdapter      - Journal Recovery Started from: Active Jou
rnal: using 5 x 20.0 Megs at: D:\java\framework_and_lib\activemq\apache-activemq
-4.1-incubator\activemq-data\journal
INFO  JournalPersistenceAdapter      - Journal Recovered: 0 message(s) in transa
ctions recovered.
INFO  TransportServerThreadSupport   - Listening for connections at: tcp://P-SUW
EI:61616
WARN  MulticastDiscoveryAgent        - brokerName not set
INFO  TransportConnector             - Connector default Started
INFO  TransportServerThreadSupport   - Listening for connections at: stomp://P-S
UWEI:61613
INFO  TransportConnector             - Connector stomp Started
INFO  NetworkConnector               - Network Connector default Started
INFO  BrokerService                  - ActiveMQ JMS Message Broker (localhost, I
D:P-SUWEI-1207-1170916242296-1:0) started     

         *。几个小提示
  1. q个仅仅是最基础的ActiveMQ的配|?很多地方都没有配|因此不要直接用这个配|用于生产系l?br />   2. 有的时候由于端口被占用,DActiveMQ错误,ActiveMQ可能需要以下端?099(JMX),61616(默认的TransportConnector)
  3. 如果没有物理|卡,或者MS的LoopBackAdpater Multicast会报一个错?/p>

     ? 试你的ActiveMQ
       
          ׃ActiveMQ是一个独立的jms provider,所以我们不需要其他Q何第三方服务器就可以马上做我们的试?~译
     example目录下面的程?br />          
   ProducerTool/ConsumerTool 是JMS参考里面提到的典型应用,Producer产生消息,Consumer消费消息
   而且q个例子q可以加入参数帮助你试刚才启动的本地ActiveMQ或者是q程的ActiveMQ

   ProducerTool [url] broker的地址,默认的是tcp://localhost:61616
                [true|flase] 是否使用topic,默认是false
         [subject] subject的名?默认是TOOL.DEFAULT
         [durabl] 是否持久化消?默认是false
         [messagecount] 发送消息数?默认?0
         [messagesize] 消息长度,默认?55
         [clientID] durable为true的时?需要配|clientID
         [timeToLive] 消息存活旉
         [sleepTime] 发送消息中间的休眠旉
         [transacte]  是否采用事务

         
          ConsumerTool [url] broker的地址,默认的是tcp://localhost:61616
                [true|flase] 是否使用topic,默认是false
         [subject] subject的名?默认是TOOL.DEFAULT
         [durabl] 是否持久化消?默认是false
         [maxiumMessages] 接受最大消息数?0表示不限?br />        
         [clientID] durable为true的时?需要配|clientID
        
         [transacte]  是否采用事务
         [sleepTime]  接受消息中间的休眠时?默认?,onMeesageҎ不休?br />          [receiveTimeOut] 接受时

          我们q样可以使用:
   java -classpath .\apache-activemq-4.1-incubator.jar;example\bin ProducerTool  tcp://192.168.3.142:61616 test.mysubject
   java -classpath .\apache-activemq-4.1-incubator.jar;example\bin ConsumerTool  tcp://192.168.3.142:61616 test.mysubject

   当然你可以用上面的参数q行更复杂的试,持久,事务

   如果出现下面的信?恭喜?你的ActiveMQ已经能够工作?br />         
  Connecting to URL: tcp://192.168.3.142:61616
  Publishing a Message with size 255 to queue: TOOL.DEFAULT
  Using non-durable publishing
  Sleeping between publish 0 ms
  Sending message: Message: 0 sent at: Thu Feb 08 15:05:34 CST 2007  ...
  Sending message: Message: 1 sent at: Thu Feb 08 15:05:34 CST 2007  ...
         。。。。。。。?/p>


  Connecting to URL: tcp://192.168.3.142:61616
  Consuming queue: test.mysubject
         Using non-durable subscription
         Received: Message: 0 sent at: Thu Feb 08 14:51:34 CST 2007  ...
         Received: Message: 1 sent at: Thu Feb 08 14:51:34 CST 2007  ...
  。。。?/p>


         ?结
     
      我们已经下蝲,启动,q且用程序测试了我们的ActiveMQ,而后面将在这个能跑得ActiveMQq一步的C?一步一步展CActiveMQ的高U特性?/p>


hk2000c 2007-11-16 17:05 发表评论
]]>
在Spring中配|JMShttp://www.aygfsteel.com/hk2000c/archive/2007/11/16/161064.htmlhk2000chk2000cFri, 16 Nov 2007 08:49:00 GMThttp://www.aygfsteel.com/hk2000c/archive/2007/11/16/161064.htmlhttp://www.aygfsteel.com/hk2000c/comments/161064.htmlhttp://www.aygfsteel.com/hk2000c/archive/2007/11/16/161064.html#Feedback0http://www.aygfsteel.com/hk2000c/comments/commentRss/161064.htmlhttp://www.aygfsteel.com/hk2000c/services/trackbacks/161064.html郁闷了三天,今天l于把JMS弄出来了Q就是发送消息,然后消息监听器接收到了消息后发送邮件给理?/p>

先看web.xml里面关于activemq的invoke

<!--调用activemq -->
    <context-param >
     <param-name>brokerURI </param-name >
     <param-value>/WEB-INF/activemq.xml </param-value >
    </context-param>
   
    <listener>
       <listener-class>org.activemq.web.SpringBrokerContextListener</listener-class>
    </listener>


郁闷了三天,今天l于把JMS弄出来了Q就是发送消息,然后消息监听器接收到了消息后发送邮件给理?/p>

先看web.xml里面关于activemq的invoke

<!--调用activemq -->
    <context-param >
     <param-name>brokerURI </param-name >
     <param-value>/WEB-INF/activemq.xml </param-value >
    </context-param>
   
    <listener>
       <listener-class>org.activemq.web.SpringBrokerContextListener</listener-class>
    </listener>

然后是在上下文中定义的JmsTemplate和activemq监听

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "
http://www.springframework.org/dtd/spring-beans.dtd">
<beans>

<!--JMS Template-->
    <bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
        <property name="connectionFactory">
      <bean class="org.activemq.ActiveMQConnectionFactory">
       <property name="brokerURL">
        <value>tcp://localhost:61616</value>
       </property>
      </bean>
     </property>
     
      <property name="defaultDestinationName" value="Hello.Queue"/>
    </bean>

   <bean id="activeMQContainer" class="org.activemq.jca.JCAContainer">
     <property name="workManager">
       <bean id="workManager" class="org.activemq.work.SpringWorkManager"/>
     </property>

     <property name="resourceAdapter">
       <bean id="activeMQResourceAdapter"
           class="org.activemq.ra.ActiveMQResourceAdapter">
         <property name="serverUrl" value="tcp://localhost:61616"/>
       </bean>
     </property>
   </bean>
 

  <!--监听 Message 的Message Driven POJO-->
    <bean id="HelloPlaceBean" class="com.officetao.jms.HelloMDP" autowire="byName"/>

  <bean id="HelloMDP" factory-method="addConnector" factory-bean="activeMQContainer">
     <property name="activationSpec">
       <bean class="org.activemq.ra.ActiveMQActivationSpec">
         <property name="destination" value="Hello.Queue"/>
         <property name="destinationType" value="javax.jms.Queue"/>
       </bean>
     </property>
     <property name="ref" value="HelloBean" />
   </bean>

</beans>

建立一个模拟的发送消息的beanQ内容如?/font>

final String mailContent = "新增单号?000的订? 金额";
  try {
            if (jmsTemplate != null)
                jmsTemplate.send(new MessageCreator() {
                    public Message createMessage(Session session)
                            throws JMSException {
                        Message message = session.createMessage();
                        message.setStringProperty("content", mailContent);
                        return message;
                    }
                });
        }
        catch (Exception e) {
            logger.error("JMS error when place order:", e);
        }

最后就是监听消息然后采取行动的bean


public class HelloMDP implements MessageListener {


 
 public void onMessage(javax.jms.Message arg0) {
  
  try   {  
            subAuthenticator   subauth   =   new   subAuthenticator("邮箱登陆?,"密码");//smtp验证   authenticator  
            props.put("mail.smtp.host","smtp.163.com");  
            props.put("mail.smtp.auth","true");  
            session   =   Session.getInstance(props,subauth);  
            MimeMessage   message   =   new   MimeMessage(session);  
            message.setRecipient(Message.RecipientType.TO,new   InternetAddress("
接收邮g的邮?/font>"));  
            message.setFrom(new   InternetAddress("
自己的邮?/font>"));  
            message.setSubject("ok");  
            message.setText("if you see it,it works!");  
            Transport.send(message);
        }  
        catch(AuthenticationFailedException   e1){  
            System.out.println("SMTP认证出错Q?);  
        }  
        catch   (MessagingException   e)   {  
            e.printStackTrace();
        }  
 
}

public   static   Properties   props   =   System.getProperties();
public   static   Session   session   =   null;  

/**  
*此内部类定义了smtp认证Ҏ  
*/  
public   class   subAuthenticator   extends   Authenticator{  
private   String   userName;  
private   String   password;  
public   subAuthenticator(String   user,String   pass){  
    userName=user;  
    password=pass;  
}  
public   PasswordAuthentication   getPasswordAuthentication(){  
    return   new   PasswordAuthentication(userName,password);  
}  



hk2000c 2007-11-16 16:49 发表评论
]]>
tomcat下应用JMS http://www.aygfsteel.com/hk2000c/archive/2007/11/16/161062.htmlhk2000chk2000cFri, 16 Nov 2007 08:48:00 GMThttp://www.aygfsteel.com/hk2000c/archive/2007/11/16/161062.htmlhttp://www.aygfsteel.com/hk2000c/comments/161062.htmlhttp://www.aygfsteel.com/hk2000c/archive/2007/11/16/161062.html#Feedback0http://www.aygfsteel.com/hk2000c/comments/commentRss/161062.htmlhttp://www.aygfsteel.com/hk2000c/services/trackbacks/161062.html JMS做ؓJ2EE的高U部分一直蒙着一层神U的面纱Q作为JMS的定制者SUN只规定了JMS规范Q象很多其他SUN产品一栯多家厂商提供了具体的实现。但是作为tomcat和RESINQ今q初宣布全部支持J2EE规范Q。这些面向低端但却被q泛应用的服务器本nq不对JMS提供支持。庆q的是openjms和activeMQ两家开源Y件提供了插g式的支持?

    在应用了一些开发框架如spring的项目里如果要用到JMSQ虽然SPRING提供了部分对JMS的支持但l过我一D|间的应用发现QOO的封装在某些地方反而成为开发过E中的障。在实现诸如监听之类的代码段里人非常的懊恼Q即使用callback(回调)有些东西仍然不能够很好的被取到?

下面׃些TOMCAT上面JMS的支持既实现做一下整理?

1.很自然的你需要下载JMS实现,?opnerJMS或者activeMQ .下蝲地址www.jmsopen.com 或www.activeMQ.com

2.服务器下载以后的具体配置在以上两个网站上都有很详l的说明Q就不再列D了?

3.和WEB服务器的整合Q首先要配置应用的web.xmlq个文g配置如下Q?

1  <context-param>
            2  <param-name>brokerURI</param-name>
            3  <param-value>/WEB-INF/activemq.xml</param-value>
            4  </context-param>
            5
            6  <listener>
            7  <listener-class>org.activemq.web.SpringBrokerContextListener</listener-class>
            8  </listener>


这一D代码放到web.xml里。注意到activemq.xml文gQ是jms服务器的具体配置Q?

<?xml version="1.0" encoding="UTF-8"?>
            <!DOCTYPE beans PUBLIC
            "-//ACTIVEMQ//DTD//EN"
            "http://activemq.org/dtd/activemq.dtd">
            <beans>
            <!-- ===================== -->
            <!-- ActiveMQ Broker Configuration -->
            <!-- ===================== -->
            <broker>
            <connector>
            <tcpServerTransport
            uri="tcp://localhost:61616"
            useAsyncSend="true"
            maxOutstandingMessages="50"/>
            </connector>
            <!-- to enable Stomp support uncomment this
            <connector>
            <serverTransport
            uri="stomp://localhost:61626"/>
            </connector>
            -->
            <persistence>
            <jdbcPersistence
            dataSourceRef="oracle-ds"/>
            </persistence>
            </broker>
            <!-- ======================= -->
            <!-- JDBC DataSource Configurations -->
            <!-- ======================= -->
            <!-- The Derby Datasource
            that will be used by the Broker -->
            <bean id="derby-ds" class=
            "org.apache.commons.dbcp.BasicDataSource"
            destroy-method="close">
            <property name="driverClassName">
            <value>
            org.apache.derby.jdbc.EmbeddedDriver
            </value>
            </property>
            <property name="url">
            <!-- Use a URL like
            'jdbc:hsqldb:hsql://localhost:9001'
            if you want to connect to a remote hsqldb -->
            <value>
            jdbc:derby:derbydb;create=true
            </value>
            </property>
            <property name="username">
            <value></value>
            </property>
            <property name="password">
            <value></value>
            </property>
            <property name="poolPreparedStatements">
            <value>true</value>
            </property>
            </bean>
            </beans>


此时Q在启动你的TOMCAT的时候会看到JMS服务器已l绑C上面?/a>

hk2000c 2007-11-16 16:48 发表评论
]]>
վ֩ģ壺 | | Ӽ| | ȷɽ| ˳| | | | ÷ӿ| | | | ũ| ϰ| | üɽ| ߺ| | ̩| | | | | | | Զ| | ¯| | Ʊ| ϻ| Ȫ| °Ͷ| | | Ƿ| | Ρɽ| Ͻ| ͭ|