HornetQ和Spring3集成Example

用HornetQ和Spring3做了一个简单的小例子,client发送指定的json串,经由HornetQ,由Server接收。

 

--------------------- client code -----------------------------------

spring 配置文件:

Xml代码 复制代码  收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util"  
  4.         xmlns:jee="http://www.springframework.org/schema/jee" xmlns:lang="http://www.springframework.org/schema/lang"  
  5.         xmlns:jms="http://www.springframework.org/schema/jms" xmlns:aop="http://www.springframework.org/schema/aop"  
  6.         xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"  
  7.   
  8.         xsi:schemaLocation="   
  9. http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd   
  10. http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd   
  11. http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd   
  12. http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-3.0.xsd   
  13. http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms-3.0.xsd   
  14. http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd   
  15. http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd   
  16. http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">  
  17.   
  18.   
  19.         <bean id="messageTopic" class="org.hornetq.api.jms.HornetQJMSClient"  
  20.                 factory-method="createTopic">  
  21.                 <constructor-arg value="com.wanmei.bitask.input.initialize.topic" />  
  22.         </bean>  
  23.   
  24.         <bean id="transportConfiguration" class="org.hornetq.api.core.TransportConfiguration">  
  25.                 <constructor-arg  
  26.                         value="org.hornetq.core.remoting.impl.netty.NettyConnectorFactory" />  
  27.                 <constructor-arg>  
  28.                         <map key-type="java.lang.String" value-type="java.lang.Object">  
  29.                                 <entry key="host" value="192.168.123.74"></entry>  
  30.                                 <entry key="port" value="5445"></entry>  
  31.                         </map>  
  32.                 </constructor-arg>  
  33.         </bean>  
  34.   
  35.         <bean id="connectionFactory" class="org.hornetq.api.jms.HornetQJMSClient"  
  36.                 factory-method="createConnectionFactoryWithoutHA">  
  37.                 <constructor-arg type="org.hornetq.api.jms.JMSFactoryType"  
  38.                         value="CF" />  
  39.                 <constructor-arg ref="transportConfiguration" />  
  40.         </bean>  
  41.   
  42.         <bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">  
  43.                 <property name="connectionFactory" ref="connectionFactory" />  
  44.                 <property name="pubSubDomain" value="true" />         
  45.         </bean>  
  46.   
  47.         <bean id="service" class="com.wanmei.service.impl.ServiceImpl">  
  48.                 <property name="jmsTemplate" ref="jmsTemplate" />  
  49.                 <property name="topic" ref="messageTopic" />  
  50.         </bean>  
  51.   
  52.   
  53.            
  54. </beans>  
java类的实现:

 

Java代码 复制代码  收藏代码
  1. public class ServiceImpl implements Service {   
  2.     private static final Logger logger = Logger.getLogger(ServiceImpl.class);   
  3.     private JmsTemplate jmsTemplate;   
  4.     private Topic topic;   
  5.   
  6.     /*  
  7.      * (non-Javadoc)  
  8.      *   
  9.      * @see com.wanmei.service.Service#sendMessage(java.util.List) 
  10.      */  
  11.     @Override  
  12.     public boolean sendMessage(List<TaskMessage> messageList) {   
  13.         return sendTopic(messageList);   
  14.     }   
  15.   
  16.     // ------------------ private method   
  17.   
  18.     private boolean sendTopic(List<TaskMessage> messageList) {   
  19.         try {   
  20.             for (TaskMessage msg : messageList) {   
  21.                 Gson gson = new Gson();   
  22.                 final String msgJson = gson.toJson(msg);   
  23.                 logger.info("start to send topic to " + topic.getTopicName()   
  24.                         + ", message : " + msgJson);   
  25.                 jmsTemplate.send(topic, new MessageCreator() {   
  26.   
  27.                     @Override  
  28.                     public Message createMessage(Session session)   
  29.                             throws JMSException {   
  30.                         TextMessage message = session   
  31.                                 .createTextMessage(msgJson);   
  32.                         return message;   
  33.                     }   
  34.                 });   
  35.             }   
  36.             return true;   
  37.         } catch (Exception e) {   
  38.             logger.error("Error: send topic failure:" + e.getMessage(), e);   
  39.             return false;   
  40.         }   
  41.     }   
  42.   
  43.     // ------------------ setter / getter   
  44.     /**  
  45.      * @return the jmsTemplate  
  46.      */  
  47.     public JmsTemplate getJmsTemplate() {   
  48.         return jmsTemplate;   
  49.     }   
  50.   
  51.     /**  
  52.      * @param jmsTemplate  
  53.      *            the jmsTemplate to set  
  54.      */  
  55.     public void setJmsTemplate(JmsTemplate jmsTemplate) {   
  56.         this.jmsTemplate = jmsTemplate;   
  57.     }   
  58.   
  59.     /**  
  60.      * @return the logger  
  61.      */  
  62.     public static Logger getLogger() {   
  63.         return logger;   
  64.     }   
  65.   
  66.     /**  
  67.      * @return the topic  
  68.      */  
  69.     public Topic getTopic() {   
  70.         return topic;   
  71.     }   
  72.   
  73.     /**  
  74.      * @param topic  
  75.      *            the topic to set  
  76.      */  
  77.     public void setTopic(Topic topic) {   
  78.         this.topic = topic;   
  79.     }   
  80.   
  81. }  
--------------------- server code -----------------------------------

spring 配置文件:

 

Xml代码 复制代码  收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util"  
  4.     xmlns:jee="http://www.springframework.org/schema/jee" xmlns:lang="http://www.springframework.org/schema/lang"  
  5.     xmlns:jms="http://www.springframework.org/schema/jms" xmlns:aop="http://www.springframework.org/schema/aop"  
  6.     xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"  
  7.   
  8.     xsi:schemaLocation="   
  9. http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd   
  10. http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd   
  11. http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd   
  12. http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-3.0.xsd   
  13. http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms-3.0.xsd   
  14. http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd   
  15. http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd   
  16. http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">  
  17.   
  18.   
  19.     <bean id="messageTopic" class="org.hornetq.api.jms.HornetQJMSClient"  
  20.         factory-method="createTopic">  
  21.         <constructor-arg value="com.wanmei.bitask.input.initialize.topic" />  
  22.     </bean>  
  23.   
  24.     <bean id="transportConfiguration" class="org.hornetq.api.core.TransportConfiguration">  
  25.         <constructor-arg  
  26.             value="org.hornetq.core.remoting.impl.netty.NettyConnectorFactory" />  
  27.         <constructor-arg>  
  28.             <map key-type="java.lang.String" value-type="java.lang.Object">  
  29.                 <entry key="host" value="192.168.123.74"></entry>  
  30.                 <entry key="port" value="5445"></entry>  
  31.             </map>  
  32.         </constructor-arg>  
  33.     </bean>  
  34.   
  35.     <bean id="connectionFactory" class="org.hornetq.api.jms.HornetQJMSClient"  
  36.         factory-method="createConnectionFactoryWithoutHA">  
  37.         <constructor-arg type="org.hornetq.api.jms.JMSFactoryType"  
  38.             value="CF" />  
  39.         <constructor-arg ref="transportConfiguration" />  
  40.     </bean>  
  41.   
  42.     <!-- this is the Message Driven POJO (MDP) -->  
  43.     <bean id="messageListener" class="com.wanmei.service.MessageListenerImpl">  
  44.         <property name="jdbcTemplate" ref="bitaskJdbcTemplate" />  
  45.     </bean>  
  46.   
  47.     <!-- and this is the message listener container -->  
  48.     <bean id="jmsContainer"  
  49.         class="org.springframework.jms.listener.DefaultMessageListenerContainer">  
  50.         <property name="connectionFactory" ref="connectionFactory" />  
  51.         <property name="destination" ref="messageTopic" />  
  52.         <property name="messageListener" ref="messageListener" />  
  53.     </bean>  
  54.   
  55.   
  56.     <!-- jdbc start -->  
  57.     <bean id="bitaskDataSource" class="org.apache.commons.dbcp.BasicDataSource"  
  58.         destroy-method="close">  
  59.         <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />  
  60.         <property name="url" value="jdbc:oracle:thin:@192.168.182.129:1521:wmdw" />  
  61.         <property name="username" value="bitask" />  
  62.         <property name="password" value="bitask" />  
  63.         <property name="validationQuery" value="select * from dual" />  
  64.     </bean>  
  65.   
  66.   
  67.     <bean id="bitaskJdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">  
  68.         <property name="dataSource" ref="bitaskDataSource" />  
  69.     </bean>  
  70.   
  71.     <bean id="transactionManager_jdbcTemplate"  
  72.         class="org.springframework.jdbc.datasource.DataSourceTransactionManager">  
  73.         <property name="dataSource" ref="bitaskDataSource" />  
  74.     </bean>  
  75.   
  76.     <aop:config>  
  77.         <aop:advisor pointcut="execution(* com.wanmei.service.*Impl*.*(..))"  
  78.             advice-ref="txAdvice_jdbcTemplate" />  
  79.     </aop:config>  
  80.   
  81.     <tx:advice id="txAdvice_jdbcTemplate" transaction-manager="transactionManager_jdbcTemplate">  
  82.         <tx:attributes>  
  83.             <tx:method name="change*" propagation="REQUIRED" />  
  84.             <tx:method name="update*" propagation="REQUIRED" />  
  85.             <tx:method name="merge*" propagation="REQUIRED" />  
  86.             <tx:method name="get*" read-only="true" />  
  87.             <tx:method name="save*" propagation="REQUIRED" />  
  88.             <tx:method name="add*" propagation="REQUIRED" />  
  89.             <tx:method name="delete*" propagation="REQUIRED" />  
  90.             <tx:method name="remove*" propagation="REQUIRED" />  
  91.             <tx:method name="hidden*" propagation="REQUIRED" />  
  92.         </tx:attributes>  
  93.     </tx:advice>  
  94.   
  95.     <!-- <bean id="lobHandler" class="org.springframework.jdbc.support.lob.DefaultLobHandler"    
  96.         lazy-init="true"/> -->  
  97.   
  98.     <!-- jdbc end -->  
  99.   
  100.   
  101. </beans>  

java类的实现:

 

Java代码 复制代码  收藏代码
  1. public class MessageListenerImpl implements MessageListener {   
  2.     private static Logger logger = Logger.getLogger(MessageListenerImpl.class);   
  3.     private JdbcTemplate jdbcTemplate;   
  4.   
  5.     /*  
  6.      * (non-Javadoc)  
  7.      *   
  8.      * @see javax.jms.MessageListener#onMessage(javax.jms.Message) 
  9.      */  
  10.     @Override  
  11.     public void onMessage(Message objMsg) {   
  12.         TextMessage msg = (TextMessage) objMsg;   
  13.         try {   
  14.             String json = msg.getText();   
  15.             logger.info("receive message : " + json);   
  16.             doJson(json);   
  17.         } catch (JMSException e) {   
  18.             logger.error(   
  19.                     "Error: receive message from topic failure: "  
  20.                             + e.getMessage(), e);   
  21.         }   
  22.     }   
  23.   
  24.     // ------------------ private method   
  25.     private void doJson(String json) {   
  26.         Gson gson = new Gson();   
  27.         TaskMessage message = gson.fromJson(json, TaskMessage.class);   
  28.         if (checkValid(message)) {   
  29.             updateProcRun(message);   
  30.         } else {   
  31.             logger.error("Error: found null value in message.");   
  32.         }   
  33.   
  34.     }   
  35.   
  36.     private void updateProcRun(final TaskMessage msg) {   
  37.         StringBuilder builder = new StringBuilder();   
  38.         builder.append(" update task_proc_run ")   
  39.                 .append(" set task_status = ?, ").append(" reload = ?, ")   
  40.                 .append(" ignore_type = ?, ").append(" initial_type = ?, ")   
  41.                 .append(" last_modified = sysdate, ")   
  42.                 .append(" exec_message = ? ")   
  43.                 .append(" where proc_time = to_date(?,'yyyy-mm-dd') ")   
  44.                 .append(" and proc_name = ? ")   
  45.                 .append(" and data_source_name = ? ");   
  46.                    
  47.   
  48.         int count = jdbcTemplate.update(builder.toString(),   
  49.                 new PreparedStatementSetter() {   
  50.   
  51.                     @Override  
  52.                     public void setValues(PreparedStatement ps)   
  53.                             throws SQLException {   
  54.                         ps.setInt(1, msg.getTaskStatus());   
  55.                         ps.setString(2, msg.getReload());   
  56.                         ps.setInt(3, msg.getIgnoreType());   
  57.                         ps.setInt(4, msg.getInitialType());   
  58.                         ps.setString(5, msg.getExecMessage());   
  59.                         ps.setString(6, msg.getProcTime());   
  60.                         ps.setString(7, msg.getProcName());   
  61.                         ps.setString(8, msg.getDataSourceName());   
  62.   
  63.                     }   
  64.                 });   
  65.         if (1 == count) {   
  66.             logger.info("update task_proc_run successfully. " + msg);   
  67.         } else {   
  68.             logger.error("update task_proc_run failure: " + msg);   
  69.         }   
  70.   
  71.     }   
  72.   
  73.     private static boolean checkValid(TaskMessage msg) {   
  74.   
  75.         if (isNull(msg.getProcName()) || isNull(msg.getProcTime())   
  76.                 || isNull(msg.getDataSourceName())   
  77.                 || isNull(msg.getIgnoreType()) || isNull(msg.getInitialType())   
  78.                 || isNull(msg.getTaskStatus()) || isNull(msg.getExecMessage())   
  79.                 || isNull(msg.getReload())) {   
  80.             logger.error("Error: some field is null. Please check args.");   
  81.             return false;   
  82.         }   
  83.   
  84.         return true;   
  85.     }   
  86.   
  87.     private static boolean isNull(Object obj) {   
  88.         return obj == null ? true : false;   
  89.     }   
  90.   
  91.     // ------------------ setter / getter   
  92.     /**  
  93.      * @return the logger  
  94.      */  
  95.     public static Logger getLogger() {   
  96.         return logger;   
  97.     }   
  98.   
  99.     /**  
  100.      * @param logger  
  101.      *            the logger to set  
  102.      */  
  103.     public static void setLogger(Logger logger) {   
  104.         MessageListenerImpl.logger = logger;   
  105.     }   
  106.   
  107.     /**  
  108.      * @return the jdbcTemplate  
  109.      */  
  110.     public JdbcTemplate getJdbcTemplate() {   
  111.         return jdbcTemplate;   
  112.     }   
  113.   
  114.     /**  
  115.      * @param jdbcTemplate  
  116.      *            the jdbcTemplate to set  
  117.      */  
  118.     public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {   
  119.         this.jdbcTemplate = jdbcTemplate;   
  120.     }   
  121.   
  122. }  

你可能感兴趣的:(spring,AOP,json,jms,encoding)