dubbo暴露出HTTP服務

dubbo暴露出HTTP服務

   點關注不迷路,歡迎再訪!		

精簡博客內容,儘量已專業術語來分享。
努力做到對每一位認可自己的讀者負責。
幫助別人的同時更是豐富自己的良機。

最近接觸dubbo+zuul,涉及到將dubbo服務暴露爲http,簡單記錄下。

前言

通常來說一個dubbo服務都是對內給內部調用的,但也有可能一個服務就是需要提供給外部使用,並且還不能有使用語言的侷限性。本章講到的沒有那麼複雜,就只是把一個不需要各種權限檢驗的dubbo服務對外提供爲HTTP服務。

準備工作

以下是本文所涉及到的一些知識點:

Spring相關知識
Java反射相關知識
SpringMVC相關知識

其實思路很簡單,利用SpringMVC提供一個HTTP接口。在該接口中通過入參進行反射找到具體的dubbo服務實現進行調用。

HttpProviderConf配置類

首先需要定義一個HttpProviderConf類用於保存聲明需要對外提供服務的包名,畢竟我們反射時需要用到一個類的全限定名:

public class HttpProviderConf {
    /**
     * 提供http訪問的包
     */
    private List<String> usePackage ;

	public List<String> getUsePackage() {
		return usePackage;
	}

	public void setUsePackage(List<String> usePackage) {
		this.usePackage = usePackage;
	}
    
}

請求響應入參、出參

HttpRequest入參

public class HttpRequest {
	
	private String param ;//入參
    private String service ;//請求service
    private String method ;//請求方法
    
	public String getParam() {
		return param;
	}
	public void setParam(String param) {
		this.param = param;
	}
	public String getService() {
		return service;
	}
	public void setService(String service) {
		this.service = service;
	}
	public String getMethod() {
		return method;
	}
	public void setMethod(String method) {
		this.method = method;
	}
}

其中param是用於存放真正調用dubbo服務時的入參,傳入json在調用的時候解析成具體的參數對象。
service存放dubbo服務聲明的interface API的包名。
method則是真正調用的方法名稱。

HttpResponse 響應

public class HttpResponse implements Serializable{
	
	private static final long serialVersionUID = -6296842759601736401L;	
	private boolean success;// 成功標誌
	private String code;// 信息碼
	private String description;// 描述
	
	public boolean isSuccess() {
		return success;
	}
	public void setSuccess(boolean success) {
		this.success = success;
	}
	public String getCode() {
		return code;
	}
	public void setCode(String code) {
		this.code = code;
	}
	public String getDescription() {
		return description;
	}
	public void setDescription(String description) {
		this.description = description;
	}
}

這裏只是封裝了常用的HTTP服務的響應數據。

暴露服務controller

@Controller
@RequestMapping("/dubboAPI")
public class DubboController implements ApplicationContextAware {

	private final static Logger logger = LoggerFactory.getLogger(DubboController.class);

	@Autowired
	private HttpProviderConf httpProviderConf;
	// 緩存作用的map
	private final Map<String, Class<?>> cacheMap = new HashMap<String, Class<?>>();
	protected ApplicationContext applicationContext;

	@ResponseBody
	@RequestMapping(value = "/{service}/{method}", method = RequestMethod.GET)
	public String api(HttpRequest httpRequest, HttpServletRequest request, @PathVariable String service,
			@PathVariable String method) {
		logger.info("ip:{}-httpRequest:{}");
		String invoke = invoke(httpRequest, service, method);
		logger.debug("callback :" + invoke);
		return invoke;

	}

	private String invoke(HttpRequest httpRequest, String service, String method) {
		httpRequest.setService(service);
		httpRequest.setMethod(method);
		HttpResponse response = new HttpResponse();

		logger.debug("input param:" + JSON.toJSONString(httpRequest));

		if (!CollectionUtils.isEmpty(httpProviderConf.getUsePackage())) {
			boolean isPac = false;
			for (String pac : httpProviderConf.getUsePackage()) {
				if (service.startsWith(pac)) {
					isPac = true;
					break;
				}
			}
			if (!isPac) {
				// 調用的是未經配置的包
				logger.error("service is not correct,service=" + service);
				response.setCode("2");
				response.setSuccess(false);
				response.setDescription("service is not correct,service=" + service);
			}

		}
		try {
			Class<?> serviceCla = cacheMap.get(service);
			if (serviceCla == null) {
				serviceCla = Class.forName(service);
				logger.debug("serviceCla:" + JSON.toJSONString(serviceCla));

				// 設置緩存
				cacheMap.put(service, serviceCla);
			}
			Method[] methods = serviceCla.getMethods();
			Method targetMethod = null;
			for (Method m : methods) {
				if (m.getName().equals(method)) {
					targetMethod = m;
					break;
				}
			}

			if (method == null) {
				logger.error("method is not correct,method=" + method);
				response.setCode("2");
				response.setSuccess(false);
				response.setDescription("method is not correct,method=" + method);
			}

			Object bean = this.applicationContext.getBean(serviceCla);
			Object result = null;
			Class<?>[] parameterTypes = targetMethod.getParameterTypes();
			if (parameterTypes.length == 0) {
				// 沒有參數
				result = targetMethod.invoke(bean);
			} else if (parameterTypes.length == 1) {
				Object json = JSON.parseObject(httpRequest.getParam(), parameterTypes[0]);
				result = targetMethod.invoke(bean, json);
			} else {
				logger.error("Can only have one parameter");
				response.setSuccess(false);
				response.setCode("2");
				response.setDescription("Can only have one parameter");
			}
			return JSON.toJSONString(result);

		} catch (ClassNotFoundException e) {
			logger.error("class not found", e);
			response.setSuccess(false);
			response.setCode("2");
			response.setDescription("class not found");
		} catch (InvocationTargetException e) {
			logger.error("InvocationTargetException", e);
			response.setSuccess(false);
			response.setCode("2");
			response.setDescription("InvocationTargetException");
		} catch (IllegalAccessException e) {
			logger.error("IllegalAccessException", e);
			response.setSuccess(false);
			response.setCode("2");
			response.setDescription("IllegalAccessException");
		}
		return JSON.toJSONString(response);
	}

	/**
	 * 獲取IP
	 * 
	 * @param request
	 * @return
	 */
	private String getIP(HttpServletRequest request) {
		if (request == null)
			return null;
		String s = request.getHeader("X-Forwarded-For");
		if (s == null || s.length() == 0 || "unknown".equalsIgnoreCase(s)) {

			s = request.getHeader("Proxy-Client-IP");
		}
		if (s == null || s.length() == 0 || "unknown".equalsIgnoreCase(s)) {

			s = request.getHeader("WL-Proxy-Client-IP");
		}
		if (s == null || s.length() == 0 || "unknown".equalsIgnoreCase(s)) {
			s = request.getHeader("HTTP_CLIENT_IP");
		}
		if (s == null || s.length() == 0 || "unknown".equalsIgnoreCase(s)) {

			s = request.getHeader("HTTP_X_FORWARDED_FOR");
		}
		if (s == null || s.length() == 0 || "unknown".equalsIgnoreCase(s)) {

			s = request.getRemoteAddr();
		}
		if ("127.0.0.1".equals(s) || "0:0:0:0:0:0:0:1".equals(s))
			try {
				s = InetAddress.getLocalHost().getHostAddress();
			} catch (UnknownHostException unknownhostexception) {
				return "";
			}
		return s;
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.applicationContext = applicationContext;
	}
}
  • 首先是定義了一個DubboController,並使用了SpringMVC的註解對外暴露HTTP服務。

  • 實現了org.springframework.context.ApplicationContextAware類, 實現了setApplicationContext()方法用於初始化Spring上下文對象,在之後可以獲取到容器裏的相應對象。

  • 核心的invoke()方法。

  • 調用時:http://127.0.0.1:8080/dubbo-provider/dubboAPI/com.dubbo.service.IDubboService/getUser。

  • 具體如上文的調用實例。先將com.dubbo.service.IDubboService、getUser賦值到httpRequest入參中。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://code.alibabatech.com/schema/dubbo
       http://code.alibabatech.com/schema/dubbo/dubbo.xsd">
	<!-- 定義了提供方應用信息,用於計算依賴關係。在dubbo-admin 或 dubbo-monitor 會顯示這個名字,方便識別 -->
	<dubbo:application name="admin-provider" owner="admin" organization="dubbox"/>
	<!-- 使用zookeeper 註冊中心暴露服務,注意要先開啓 zookeeper -->
	<dubbo:registry address="zookeeper://127.0.0.1:2181"/>
	<!-- 用dubbo協議在20880端口暴露服務 -->
	<dubbo:protocol name="dubbo" port="20880"/>
	<!-- 用dubbo 協議實現定義好的 api 接口 -->
	<dubbo:service interface="com.dubbo.service.IDubboService" ref="dubboService" protocol="dubbo"/>
	<dubbo:service interface="com.dubbo.service.IUserService" ref="userService" protocol="dubbo"/>
	<!--dubbo服務暴露爲http服務-->
    <bean class="com.dubbo.http.conf.HttpProviderConf">
        <property name="usePackage">
            <list>
            	   <!--需要暴露服務的接口包名,可多個-->
                <value>com.dubbo.service</value>
            </list>
        </property>
    </bean>
</beans>

其中的com.dubbo.service就是自己需要暴露的包名,可以多個。

  • 接着在緩存map中取出反射獲取到的接口類類型,如果獲取不到則通過反射獲取,並將值設置到緩存map中,這樣不用每次都反射獲取,可以節省系統開銷(反射很耗系統資源)。
  • 接着也是判斷該接口中是否有傳入的getUser方法。
  • 取出該方法的參數列表,如果沒有參數則直接調用。
  • 如果有參數,判斷個數。這裏最多隻運行一個參數。也就是說在真正的dubbo調用的時候只能傳遞一個BO類型,具體的參數列表可以寫到BO中。因爲如果有多個在進行json解析的時候是無法賦值到兩個參數對象中去的。
  • 之後進行調用,將調用返回的數據進行返回即可。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章