当前位置:首页 > 开发 > 互联网 > 正文

Hessian学习笔记之HessianRPC

发表于: 2015-07-15   作者:zh-workhard-Java   来源:转载   浏览:
摘要: 一、总述        在Hessian学习笔记之上传文件这一篇中,通过一个实例讲解了如何通过Hessian实现上传文件。Hessian最主要的特征之一就是远程过程调用(Remote Procedure Call,RPC)。下面通过一个简单的实例说明。   二、实例展示      1、环境搭建  

一、总述

       在Hessian学习笔记之上传文件这一篇中,通过一个实例讲解了如何通过Hessian实现上传文件。Hessian最主要的特征之一就是远程过程调用(Remote Procedure Call,RPC)。下面通过一个简单的实例说明。

 

二、实例展示

     1、环境搭建

          开发工具:eclipse + tomcat。

          服务端:JavaWeb工程。例如,实例中本人创建的JavaDemo工程。

          客户端:Java工程。例如,实例中本人创建的HessianClient工程。

     

     2、代码实现

           a.实体类:        

import java.io.Serializable;
import java.util.Date;

public class Person implements Serializable {
	private static final long serialVersionUID = 8268991521882061845L;
	
	private int id;
	private String name ;
	private Long phone ;
	private boolean gender;
	private double height;
	private float weight;
	private String[] address;
	private Date birthday;
	
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Long getPhone() {
		return phone;
	}
	public void setPhone(Long phone) {
		this.phone = phone;
	}
	public boolean isGender() {
		return gender;
	}
	public void setGender(boolean gender) {
		this.gender = gender;
	}
	public double getHeight() {
		return height;
	}
	public void setHeight(double height) {
		this.height = height;
	}
	public float getWeight() {
		return weight;
	}
	public void setWeight(float weight) {
		this.weight = weight;
	}
	public String[] getAddress() {
		return address;
	}
	public void setAddress(String[] address) {
		this.address = address;
	}
	public Date getBirthday() {
		return birthday;
	}
	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}
	
	public String toString(){
		return "name:" + this.name + " phone:" + this.phone;
	}
}

 

 

           b.服务端HessianServer接口           

import java.io.InputStream;
import java.util.List;

import com.zh.hessian.entry.Person;

public interface HessianServer {
   public String say();
   public String say(String str);
   public List<Person> getPerson();
   public Person getPersonById(int id);
   public boolean upload(String filename,InputStream data);
   public byte[] download(String filename);
}

          

 

         c.服务端HessianServer接口实现         

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Random;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;

import com.zh.hessian.entry.Person;

public class HessianServerImpl implements HessianServer {
    //上传或下载文件的地址
	private static String file_Path = "D:/tools/LearningByMyself/hessian/temp/";
	
	private static Person[] persons = new Person[5];
    static {
    	Random random = new Random();
    	for(int i=0;i<persons.length;i++){
    		persons[i] = new Person();
    		persons[i].setId(i);
    		persons[i].setGender(random.nextBoolean());
    		persons[i].setName("name-" + i);
    		persons[i].setPhone(random.nextLong());
    		persons[i].setHeight(random.nextDouble());
    		persons[i].setWeight(random.nextFloat());
    		persons[i].setAddress(new String[]{"Address" + random.nextInt(),"Address" + random.nextInt()});
    		
    		Calendar calendar = Calendar.getInstance();
    		calendar.set(Calendar.DATE, i+1);
    		persons[i].setBirthday(calendar.getTime());
    	}
    }
    	@Override
	public String say() {
		return "Hello HessianRPC " + new Date().toString();
	}

	@Override
	public String say(String str) {
		return "Welcome" + str;
	}

	@Override
	public List<Person> getPerson() {
		return Arrays.asList(persons);
	}

	@Override
	public Person getPersonById(int id) {
		for(Person person : persons){
			if(person.getId() == id){
				return person ;
			}
		}
		return null;
	}
	@Override
	public boolean upload(String filename, InputStream data) {
		List<String> temp;
        try {
            temp = IOUtils.readLines(data);
            String filePath = file_Path + filename;
            FileUtils.writeLines(new File(filePath), temp);
            System.out.println("Upload file to " + filePath);
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
	}

	@Override
	public byte[] download(String filename) {
		String filePath = file_Path + filename;
        InputStream data = null;
        try {
            data = new FileInputStream(filePath);
            int size = data.available();
            byte[] buffer = new byte[size];
            IOUtils.read(data, buffer);
            return buffer;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            IOUtils.closeQuietly(data);
        }
    }
}

          

 

         d.web.xml配置      

<servlet>
     <!-- RPC HessianServlet -->
     <servlet-name>hessianRPC</servlet-name>
     <servlet-class>com.caucho.hessian.server.HessianServlet</servlet-class>
     
     <!-- 服务端配置 -->
     <init-param>
          <param-name>service-class</param-name>
          <param-value>com.zh.hessian.server.HessianServerImpl</param-value>
     </init-param>
     
     <!-- 客户端配置(可选) -->
     <init-param>
          <param-name>api-class</param-name>
          <param-value>com.zh.hessian.server.HessianServer</param-value>
     </init-param>
  </servlet>
  <servlet-mapping>
     <servlet-name>hessianRPC</servlet-name>
     <url-pattern>/hessianRPC</url-pattern>
  </servlet-mapping>

          

 

         e.检验服务端

         启动Tomcat后,在浏览器中输入:http://localhost:8080/JavaDemo/hessianRPC,回车后,出现如下信息:

  Hessian Requires POST

则服务端可用。

         

         f.文件打包:

         将服务端的HessianServer文件和实体类Person打成Jar包,添加到客户端的工程。例如,实例中打成的两个jar包:HessianRPC.jar和Person.jar。

 

         g.客户端实现     

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import org.apache.commons.io.IOUtils;

import com.caucho.hessian.client.HessianProxyFactory;
import com.zh.hessian.entry.Person;
import com.zh.hessian.server.HessianServer;

public class HessianClient {
    //Hessian RPC远程服务url
	private static final String url = "http://127.0.0.1:8080/JavaDemo/hessianRPC";
		
    public static void main(String[] args) throws Exception{
    	//创建HessianProxyFactory实例
    	HessianProxyFactory factory = new HessianProxyFactory();
    	
        //开启方法重载
        factory.setOverloadEnabled(true); 
        
        //获得Hessian服务的远程引用
        HessianServer hessianServer = (HessianServer)factory.create(HessianServer.class, url);
 
        //调用方法
        System.out.println("call say():" + hessianServer.say());
        System.out.println("call say(\"Tom\"):" + hessianServer.say("Tom"));
        System.out.println("call getPerson():");
 
        //调用方法获取集合对象
        List<Person> persons = hessianServer.getPerson();
        if (null != persons && persons.size() > 0) {
            for (Person p : persons) {
                System.out.println(p.toString());
            }
        } else {
            System.out.println("No person.");
        }
 
        //通过参数调用方法获取对象
        int id = 2;
        System.out.println(String.format("call getPersonById(%d)", id));
        Person person = hessianServer.getPersonById(id);
        if (null != person) {
            System.out.println(person.toString());
        } else {
            System.out.println("Id is " + id + " person not exist.");
        }
        
        uploadFile(hessianServer);
        downloadFile(hessianServer);      
    }
    
    /**
     * 上传文件
     * @param hessianServer
     */
    public static void uploadFile(HessianServer hessianServer){
    	String file = "D:/papers/work_opt.txt";//需要上传的文件
        String file_path= "D:/tools/LearningByMyself/hessian/temp";//上传文件到服务器的路径
        InputStream data = null;
        try {
            data = new BufferedInputStream(new FileInputStream(file));
            if (hessianServer.upload("work_opt.txt", data)) {
                System.out.println("Upload file " + file_path + " succeed.");
            } else {
                System.out.println("Upload file " + file_path + " failed.");
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(data);
        }
    }
    
    /**
     * 下载文件
     * @param hessianServer
     */
    public static void downloadFile(HessianServer hessianServer){
    	byte[] temp = null ;
        String file_name = "work_opt.txt" ;
        String download_path = "D:/tools/LearningByMyself/hessian/temp_write/";//文件下载后存放的路径
        try { 
            temp = hessianServer.download(file_name);
            if (null != temp) {
                FileWriter output = new FileWriter(download_path + file_name);
                IOUtils.write(temp, output, "UTF-8");
                System.out.println("Download file " + download_path + " succeed.");
                output.close();
            } else {
                System.out.println("Download file " + download_path + " failed.");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

 

三、测试结果

    call say():Hello HessianRPC Wed Jul 15 10:50:09 CST 2015

    call say("Tom"):WelcomeTom

    call getPerson():

    name:name-0 phone:838556501517807978

    name:name-1 phone:284031862309934267

    name:name-2 phone:-1412022783575136070

    name:name-3 phone:-6202617782412451628

    name:name-4 phone:6912293883557709050

    call getPersonById(2)

    name:name-2 phone:-1412022783575136070

    Upload file D:/tools/LearningByMyself/hessian/temp succeed.

    Download file D:/tools/LearningByMyself/hessian/temp_write/ succeed.

    

    最后在对应的路径下找到上传和下载的文件。例如,实例中的work_opt.txt文件,上传文件:D:\tools\LearningByMyself\hessian\temp,下载文件:D:\tools\LearningByMyself\hessian\temp_write。

Hessian学习笔记之HessianRPC

  • 0

    开心

    开心

  • 0

    板砖

    板砖

  • 0

    感动

    感动

  • 0

    有用

    有用

  • 0

    疑问

    疑问

  • 0

    难过

    难过

  • 0

    无聊

    无聊

  • 0

    震惊

    震惊

编辑推荐
一、远程通讯协议的基本原理   网络通信需要做的就是将流从一台计算机传输到另外一台计算机,基于
hessian是一个采用二进制格式传输的服务框架,相对传统soap web service,更轻量,更快速。官网地址
Hessian是一个轻量级的remoting onhttp工具,使用简单的方法提供了RMI的功能。 相比WebService,Hes
日前,做了一个小练习,采用的hessian框架实现的网络访问,其中在传统的hessian网络访问请求中加入
Hessian学习总结: 最近学习了一下hessian,发现用hessian来实现远程调用确实很简单易用。hessian序
【客户端】 我们在客户端是如何使用hessian呢? String url = "http://localhost:8080/Hello/hello";
紧接着上一篇,我们来看看另一个序列化类 JavaSerializer(参考源码版本3.0.13)。 这个类一般是用来
今天重新看了一下Hessian的序列化类,发现了一个之前被自己忽略的地方,而这应该也是Hessian序列化较
在上一笔记中记录了如何创建最简单的Hessian服务,并使用Java远程调用。Hessian服务,本文将介绍如
10 Hessian
一、简介 Hessian是由caucho提供的一个基于binary-RPC实现的远程通讯library。   1、是基于什么协
版权所有 IT知识库 CopyRight © 2009-2015 IT知识库 IT610.com , All Rights Reserved. 京ICP备09083238号