JMS解決系統間通信問題
近期在給公司項目做二次重構,將原來龐大的系統拆分成幾個小系統。系統與系統之間通過接口調用,系統間通信有非常多方式,如系統間通信接口做成請求controller,只是這樣不方便也不安全,經常使用的方式是使用rpc技術,能夠使用webservices技術等等。因為我的架構是使用spring,並且spring在集成這塊做的非常不錯。如hessian,blurp,webservices。httpinvoke,rmi,jms等,我這裏採用的是jms技術。
廢話不多說間代碼。
場景描寫敘述:A系統須要調用B系統提供的接口
1、B系統提供的接口
a、創建接口
package com.maimai.test.jmsservice; import com.maimai.db_bean.User; public interface AlertService { public String sendStr(String str); public void print_r(String str); public User findById(long id); }
b、創建接口實現類
package com.maimai.test.jmsservice; import org.springframework.beans.factory.annotation.Autowired; import com.maimai.dao.UserDao; import com.maimai.db_bean.User; public class AlertServiceImpl implements AlertService { @Autowired private UserDao userDao; public String sendStr(final String str) { System.out.println("========收到的信息======"+str+"================"); return "來自服務端的返回信息,我接收到數據了 ..."; } public void print_r(String str){ System.out.println("========收到的信息======"+str+"================"); } public User findById(long id) { User user = userDao.findById(id); return user; } }
amq配置
<amq:connectionFactory id="connectionFactory" brokerURL="tcp://localhost:61616" /> <amq:queue id="queue" physicalName="mail.queue"></amq:queue>
jms配置
<jms:listener-container connection-factory="connectionFactory"> <jms:listener destination="mail.queue" ref="jmsreciever" method="getStr"/> <jms:listener destination="couponMessage.queue" ref="jsmRecieveMessage" method="receiveJMSMessage"/> <jms:listener destination="spitter.alert.queue" ref="alertServiceExporter"/> </jms:listener-container>
//備註這裏僅僅須要destination="spitter.alert.queue"
d、將接口導出成jms服務配置
<bean id="alertServiceExporter" class="org.springframework.jms.remoting.JmsInvokerServiceExporter" p:service-ref="alertService" p:serviceInterface="com.maimai.test.jmsservice.AlertService"/> <bean id="alertService" class="com.maimai.test.jmsservice.AlertServiceImpl"/>
備註:此刻B系統提供接口準備工作做完了,接下來是A系統的工作
2、A系統調用B系統提供的服務
a、將B系統中接口所在包拷貝到A系統中。或者將B系統接口打包jar導入到A系統中
備註:僅僅須要將com.maimai.test.jmsservice.AlertService這個復制過來就可以,不須要實現類
b、在A系統中配置amq
配置amq
<amq:connectionFactory id="connectionFactory" brokerURL="tcp://localhost:61616" /> <amq:queue id="alertServiceQueue" physicalName="spitter.alert.queue"></amq:queue>
配置jms工廠
<bean id="alertService" class="org.springframework.jms.remoting.JmsInvokerProxyFactoryBean" > <property name="connectionFactory" ref="connectionFactory" /> <property name="queueName" value="spitter.alert.queue" /> <property name="serviceInterface" value="com.maimai.test.jmsservice.AlertService"></property> </bean>
備註:到此,我們都已經配置好了,接下來是A系統開始調用B系統提供的接口服務
package com.maimai.action; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.apache.struts2.interceptor.ServletRequestAware; import org.springframework.beans.factory.annotation.Autowired; import com.maimai.db_bean.Product; import com.maimai.db_bean.ProductBrand; import com.maimai.db_bean.ProductCategory; import com.maimai.db_bean.ProductCommentRecord; import com.maimai.db_bean.ProductDetail; import com.maimai.db_bean.ProductLimitedTime; import com.maimai.db_bean.ProductType; import com.maimai.db_bean.ScannedProduct; import com.maimai.db_bean.User; import com.maimai.db_bean.HotProduct; import com.maimai.db_bean.UserShop; import com.maimai.engine.AfterSaleEngine; import com.maimai.engine.DealEngine; import com.maimai.engine.ProductEngine; import com.maimai.engine.UserEngine; import com.maimai.service.UserShopService; import com.maimai.test.jmsservice.AlertService; import com.maimai.util.Constant; import com.maimai.util.IKAnalyzerUtil; import com.maimai.util.Util; import com.opensymphony.xwork2.ActionSupport; /** * 商品Action * */ public class ProductAction extends ActionSupport implements ServletRequestAware { /** * 序列號 */ private static final long serialVersionUID = 495219298210322438L; private HttpServletRequest request; // 商品engine @Autowired private ProductEngine productEngine; // 用戶engine @Autowired private UserEngine userEngine; // 交易Engine @Autowired private DealEngine dealEngine; // 售後服務Engine @Autowired private AfterSaleEngine afterSaleEngine; @Autowired private UserShopService userShopService; @Autowired AlertService alertService; /************ * 進入商品具體頁 * */ public String ToProductDetail(){ // 獲取商品id String str = this.alertService.sendStr("你好,中國"); //調用B系統接口 System.out.println("=================="+str+"===================="); this.alertService.print_r("你好,哈哈哈。成功了!!!!"); <span style="font-family: Arial, Helvetica, sans-serif;">//調用B系統接口</span> User user1 = this.alertService.findById(10); <span style="font-family: Arial, Helvetica, sans-serif;">//調用B系統接口</span> System.out.println(user1.toString()); long productId = Long.parseLong(this.request.getParameter("pid")); // 依據id獲取商品 Product product = this.productEngine.getProductById(productId); if (Util.isNullOrEmpty(product)) { return "ProductError"; } this.request.setAttribute("product", product); //added by sam 店鋪查詢 UserShop userShop = new UserShop(); if(product.getUserId() != 0 ){ userShop = this.userShopService.findByUserId(product.getUserId()); } this.request.setAttribute("userShop", userShop); //ended by sam // 依據商品所屬分類id獲取商品列表 List<Product> sameCategoryProducts = this.productEngine.getProductsByCategoryId(product.getCategoryId(), 1, 5); this.request.setAttribute("sameCategoryProducts", sameCategoryProducts); /** 記錄瀏覽了此商品 **/ try { // 獲取當前登錄用戶 User user = this.userEngine.getCurrentuser(); ScannedProduct scannedProduct = new ScannedProduct(); scannedProduct.setProductId(productId); scannedProduct.setUserId(user.getId()); this.productEngine.getProductService().saveScannedProduct(scannedProduct); } catch (Exception e) { //e.printStackTrace(); } return "ToProductDetail"; } }A系統調用B系統成功信息例如以下:
========收到的信息======你好,中國================
2015-12-31 09:35:52,261 [org.springframework.jms.listener.DefaultMessageListenerContainer#2-2] DEBUG [org.springframework.remoting.support.RemoteInvocationTraceInterceptor] - Finished processing of JmsInvokerServiceExporter remote call: com.maimai.test.jmsservice.AlertService.sendStr
==================來自服務端的返回信息。我接收到數據了 ...====================
2015-12-31 09:35:52,332 [org.springframework.jms.listener.DefaultMessageListenerContainer#2-2] DEBUG [org.springframework.jms.listener.DefaultMessageListenerContainer] - Received message of type [class org.apache.activemq.command.ActiveMQObjectMessage] from
consumer [ActiveMQMessageConsumer { value=ID:PC-20150906SEWA-53438-1451525683864-0:21:1:1, started=true }] of session [ActiveMQSession {id=ID:PC-20150906SEWA-53438-1451525683864-0:21:1,started=true}]
2015-12-31 09:35:52,333 [org.springframework.jms.listener.DefaultMessageListenerContainer#2-2] DEBUG [org.springframework.remoting.support.RemoteInvocationTraceInterceptor] - Incoming JmsInvokerServiceExporter remote call: com.maimai.test.jmsservice.AlertService.print_r
========收到的信息======你好,哈哈哈,成功了!!!!================
2015-12-31 09:35:52,606 [org.springframework.jms.listener.DefaultMessageListenerContainer#2-2] DEBUG [org.springframework.remoting.support.RemoteInvocationTraceInterceptor] - Finished processing of JmsInvokerServiceExporter remote call: com.maimai.test.jmsservice.AlertService.findById
User [accountImage=sysImg/user/10/account/account20150810170819.jpg, age=12, [email protected], idCode=34081119, idImageBack=sysImg/user/id/11510411712110199104971114953514853535448575448/11510411712110199104971114953514853535448575448Back.jpg, idImageFore=sysImg/user/id/11510411712110199104971114953514853535448575448/11510411712110199104971114953514853535448575448Fore.png,
isLocked=0, loginName=samtest, password=`O怾,u?
攠聉?, qq=526713869, realName=張三, registTime=2015-01-26 09:56:04, sex=f, userType=0, telNum=15305560960, status=0]
JMS解決系統間通信問題