Spring HttpInvoke 客户端调用代码实现

package com.lyis.core.httpinvoke;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import org.springframework.remoting.httpinvoker.HttpInvokerProxyFactoryBean;

import com.lyis.core.consts.DomainConst;
import com.lyis.core.httpinvoke.service.AccountRemoteService;
import com.lyis.core.httpinvoke.service.ActionRemoteService;
import com.lyis.core.httpinvoke.service.LoginLogRemoteService;
import com.lyis.core.httpinvoke.service.PushRemoteService;
import com.lyis.core.httpinvoke.service.ShowRemoteService;
import com.lyis.core.httpinvoke.service.UserRemoteService;

/**
 * 远程调用工具类
 * 
 * @author Johnson
 * @version Saturday March 2nd, 2013
 */
public class HttpInvokeFactory {

	private static ConcurrentMap<String, Object> serviceProxyMap = new ConcurrentHashMap<String, Object>();
	private static ConcurrentMap<Class<?>, String> serviceUrlMap = new ConcurrentHashMap<Class<?>, String>();

	/**
	 * 注册默认服务地址
	 */
	static {
		serviceUrlMap.put(AccountRemoteService.class, DomainConst.ACCOUNT
				+ "/remoting/AccountRemoteService");
		serviceUrlMap.put(ShowRemoteService.class, DomainConst.ACCOUNT
				+ "/remoting/ShowRemoteService");
		serviceUrlMap.put(ActionRemoteService.class, DomainConst.ACCOUNT
				+ "/remoting/ActionRemoteService");
		serviceUrlMap.put(LoginLogRemoteService.class, DomainConst.ACCOUNT
				+ "/remoting/LoginLogRemoteService");
		serviceUrlMap.put(UserRemoteService.class, DomainConst.ACCOUNT
				+ "/remoting/UserRemoteService");
		serviceUrlMap.put(PushRemoteService.class, DomainConst.ACCOUNT
				+ "/remoting/PushRemoteService");
	}

	/**
	 * 创建服务对象
	 * 
	 * @param <T>
	 * @param serviceUrl
	 * @param clazz
	 * @return
	 */
	@SuppressWarnings("unchecked")
	private static <T> T createService(String serviceUrl, Class<T> clazz) {
		HttpInvokerProxyFactoryBean bean = new HttpInvokerProxyFactoryBean();
		bean.setServiceUrl(serviceUrl);
		bean.setServiceInterface(clazz);
		bean.afterPropertiesSet();
		return (T) bean.getObject();
	}

	/**
	 * 添加服务地址
	 * 
	 * @param clazz
	 * @param serviceUrl
	 */
	public static void put(Class<?> clazz, String serviceUrl) {
		if (serviceUrlMap.containsKey(clazz)) {
			return;
		}
		serviceUrlMap.put(clazz, serviceUrl);
	}

	/**
	 * 获取服务对象
	 * 
	 * @param <T>
	 * @param clazz
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static <T> T getService(Class<T> clazz) {
		String serviceUrl = serviceUrlMap.get(clazz);
		if (serviceUrl == null) {
			return null;
		}
		Object service = serviceProxyMap.get(serviceUrl);
		if (service == null) {
			service = HttpInvokeFactory.createService(serviceUrl, clazz);
			serviceProxyMap.put(serviceUrl, service);
		}
		return (T) service;
	}
}

你可能感兴趣的:(Spring HttpInvoke 客户端调用代码实现)