温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

使用servlet实现远程调用(2)

发布时间:2020-08-07 00:06:23 来源:ITPUB博客 阅读:218 作者:tigerflower 栏目:编程语言

使用servlet实现远程调用的修改

全部代码:

[@more@]package com.witframework.remote;

/**
* 对远程调用请求的封装
* @author wuxinyang
*/
public class HttpInvokeRequest implements java.io.Serializable,Cloneable{
private static final long serialVersionUID = 1L;
//目标地址,如果为localhost则为本地方法调用。
private String serverAddress;
private String serviceType="spring";
//spring bean的配置名称,如果配置了该值则通过spring配置装载service。
//服务的接口class名称,必须带包名
private String serviceName;
//要调用的方法名称
private String methodName;
//传入的参数列表
private Object[] arguments;
private boolean resultAsXml;
/**
* serverAddress=localhost:8080
* serviceAddress=spring:service/getAll
* serviceAddress=class:service/getAll
*/
public HttpInvokeRequest(String serviceAddress) {
int typeIndex=serviceAddress.indexOf(":");
if(typeIndex>0){
serviceType=serviceAddress.substring(0,serviceAddress.indexOf(":"));
this.serviceName=serviceAddress.substring(serviceAddress.lastIndexOf(":")+1,serviceAddress.lastIndexOf("/"));
}else{
this.serviceName=serviceAddress.substring(0,serviceAddress.indexOf("/"));
}
this.methodName=serviceAddress.substring(serviceAddress.lastIndexOf("/")+1);
}

public HttpInvokeRequest(String serverAddress,String serviceAddress) {
this(serviceAddress);
this.serverAddress=serverAddress;
}
/**
* 清除参数列表
*/
public void clearArguments(){
arguments=null;
}
public void setArgument(Object... args){
arguments=args;
}
public Object[] getArguments() {
return arguments;
}
public String getMethodName() {
return methodName;
}
public String getServerAddress() {
return serverAddress;
}
public String getServiceName() {
return serviceName;
}
public String getServiceType(){
return serviceType;
}
@Override
public Object clone() throws CloneNotSupportedException{
return super.clone();
}
public void setServerAddress(String serverAddress) {
this.serverAddress = serverAddress;
}
public void setServiceType(String serviceType) {
this.serviceType = serviceType;
}
public void setServiceName(String serviceName) {
this.serviceName = serviceName;
}
public void setMethodName(String methodName) {
this.methodName = methodName;
}

public boolean isResultAsXml() {
return resultAsXml;
}

public void setResultAsXml(boolean resultAsXml) {
this.resultAsXml = resultAsXml;
}
}
package com.witframework.remote;

import org.apache.commons.beanutils.MethodUtils;

/**
* 简单远程调用请求解析执行类
* @author wuxinyang
*
*/
class LocalRequestProcessor {
public static Object processorLocalhost(HttpInvokeRequest request){
String serviceName = request.getServiceName();
try {
Object service;
if(request.getServiceType().equalsIgnoreCase("spring")){
service=com.witframework.core.BeanFactory.getBean(serviceName);
}
else{
service = Class.forName(serviceName).newInstance();
}
Object object= MethodUtils.invokeExactMethod(service, request.getMethodName(),request.getArguments());
if(request.isResultAsXml())
object=Java2Xml.toXml(object);
return object;
} catch (Exception e) {
return new HttpInvokerException("处理远程调用时发生错误.",e);
}
}
}
package com.witframework.remote;

import java.io.Closeable;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.URL;

import org.apache.log4j.Logger;



/**
* 简单远程调用请求解析执行类
* @author wuxinyang
*
*/
public class RemoteExecutor {
static Logger logger = Logger.getLogger ( RemoteExecutor.class) ;
/**
* 执行远程调用
* @return 返回值对象
* @throws HttpInvokerException 在授权验证失败或调用参数错误时 */
public static Object invoke(HttpInvokeRequest httpInvokeRequest) throws HttpInvokerException {
return invoke(httpInvokeRequest,false);
}
public static Object invoke(HttpInvokeRequest httpInvokeRequest,boolean resultAsXml) throws HttpInvokerException {
Object result;
long startTime=System.currentTimeMillis();
if(null==httpInvokeRequest)
throw new HttpInvokerException("not set HttpInvokerRequest.");
if(httpInvokeRequest.getServerAddress().equals("localhost")){
result= LocalRequestProcessor.processorLocalhost(httpInvokeRequest);
if(resultAsXml)
result=Java2Xml.toXml(result);
return result;
}
try {
HttpInvokeRequest request=(HttpInvokeRequest)httpInvokeRequest.clone();
request.setResultAsXml(resultAsXml);
result= processorRemote(request);
} catch (CloneNotSupportedException e) {
throw new HttpInvokerException(e);
}
long usetime=System.currentTimeMillis()-startTime;
logger.debug("call remote service completed. used time:"+usetime);
return result;
}
private static Object processorRemote(HttpInvokeRequest httpInvokeRequest) throws HttpInvokerException {
java.net.URLConnection con;
ObjectOutputStream dataout=null;
InputStream conis=null;
OutputStream conos=null;
ObjectInputStream in=null;
try {
URL url = new URL("http://"+httpInvokeRequest.getServerAddress()+"/httpinvoker");
con = url.openConnection();
con.setUseCaches(false);
con.setDoOutput(true);
con.setDoInput(true);
con.setRequestProperty("Content-type", "application/octest-stream");
conos=con.getOutputStream();
dataout = new ObjectOutputStream(conos);
dataout.writeObject(httpInvokeRequest);
conis=con.getInputStream();
in = new ObjectInputStream(conis);
Object obj = in.readObject();
if(obj instanceof RuntimeException){
throw (RuntimeException)obj;
}
return obj;
}catch (Exception e) {
throw new HttpInvokerException(e);
}finally{
close(in);
close(conos);
close(conis);
close(dataout);
}
}
private static void close(Closeable object){
try {
object.close();
} catch (Exception e) {
}
}
}
package com.witframework.remote;

import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.apache.log4j.Logger;




/**
* 远程调用的服务器处理类,要是有remote包,需要在提供远程服务的应用上配置
* WitRemoteServlet,如下:
*

*
* WitRemoteServlet
* com.witframework.remote.WitRemoteServlet
*

*
* WitRemoteServlet
* /httpinvoker
*

*

*
* @author wuxinyang
*/
public class WitRemoteServlet extends GenericServlet {
static Logger logger = Logger.getLogger ( WitRemoteServlet.class) ;
@Override
public void service(ServletRequest req, ServletResponse resp) throws ServletException, IOException {
ObjectInputStream in = new ObjectInputStream(req.getInputStream());
resp.setContentType("application/octest-stream");
HttpInvokeRequest request = null;
try {
request = (HttpInvokeRequest)in.readObject();
logger.debug("invoke request:"+request.toString());
} catch (ClassNotFoundException e) {
outObject(resp,new HttpInvokerException(e));
}
outObject(resp,LocalRequestProcessor.processorLocalhost(request));
}

private void outObject(ServletResponse resp,Object o) {
ByteArrayOutputStream byteout = new ByteArrayOutputStream();
ObjectOutputStream out=null;
ServletOutputStream servletout=null;
try {
out = new ObjectOutputStream(byteout);
out.writeObject(o);
byte buf[] = byteout.toByteArray();
resp.setContentLength(buf.length);
servletout = resp.getOutputStream();
servletout.write(buf);
} catch (Exception e) {
e.printStackTrace();
}finally{
close(servletout);
close(out);
}
}
private static void close(Closeable object){
try {
object.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

package com.witframework.remote;


/**
* 简单远程调用异常类型定义类
* @author wuxinyang
*
*/
public class HttpInvokerException extends RuntimeException{
private static final long serialVersionUID = 20080804L;
public HttpInvokerException(String msg) {
super(msg);
}
public HttpInvokerException(Throwable cause) {
super(cause);
}
public HttpInvokerException(String msg,Throwable cause){
super(msg,cause);
}

}
向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI