首页 > 代码库 > JMS解决系统间通信问题

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;
	}
	
}
c、配置amq和jms

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=http://www.mamicode.com/"spitter.alert.queue" />>

备注:到此,我们都已经配置好了,接下来是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=http://www.mamicode.com/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=526713869@qq.com, 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解决系统间通信问题