基于二进制RPC协议法的轻量级远程调用框架 ---- Hessian

使用Java创建Hessian服务有四个步骤:

1、创建Java接口作为公共API                             (client和server端 创建一个相同的借口)

2、使用HessianProxyFactory创建一个客户端       (client端)

3、创建服务实现类,继承HessianServlet             (server端)

4、在servlet引擎中配置服务。                            (server端)

代码示例:

server端:

package com.lin.hessian.service;
public interface Basic {
public String sayHello();
}
package com.lin.hessian.service;
import com.caucho.hessian.server.HessianServlet;
public class LinyService extends HessianServlet implements Basic{
private String message = "wowwowowowowow";
@Override
public String sayHello() {
return message;
}
}
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>HessianWeb</display-name>
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>com.caucho.hessian.server.HessianServlet</servlet-class>
<init-param>
<param-name>home-class</param-name>
<param-value>com.lin.hessian.service.BasicService</param-value>
</init-param>
<init-param>
<param-name>home-api</param-name>
<param-value>com.lin.hessian.service.Basic</param-value>
</init-param>
</servlet> <servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping> <servlet>
<servlet-name>liny</servlet-name>
<servlet-class>com.lin.hessian.service.LinyService</servlet-class>
</servlet> <servlet-mapping>
<servlet-name>liny</servlet-name>
<url-pattern>/liny</url-pattern>
</servlet-mapping>
</web-app>

client端:

package com.liny.hessian.service;
public interface Basic {
public String sayHello();
}
package com.lin.hessian.client;
import java.net.MalformedURLException;
import com.caucho.hessian.client.HessianProxyFactory;
import com.liny.hessian.service.Basic;
public class HessianClient {
public static void main(String[] args) throws MalformedURLException{
     //String url = "http://localhost:8080/HessianWeb/hello";
String url = "http://localhost:8080/HessianWeb/liny";
HessianProxyFactory factory = new HessianProxyFactory();
Basic basic = (Basic)factory.create(Basic.class, url);
System.out.println(basic.sayHello());
}
}

client端要定义一个同server端一模一样的接口Basic,然后通过HessianProxyFactory获得代理,并调用远程服务的方法。

上一篇:中文版Windows 7下设置日语格式布局的键盘


下一篇:SOA,SOAP,RPC,以及 RPC协议与 REST 协议之间的关系(搜狗)