Hessian学习笔记之HessianRPC

一、总述

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

 

二、实例展示

     1、环境搭建

          开发工具:eclipse + tomcat。

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

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

     2、服务端代码实现

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;
	}
}

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);
}

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);
        }
    }
}

<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>

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

    Hessian Requires POST

则服务端可用。

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


      3.客户端代码实现

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。



阅读更多
想对作者说点什么?
相关热词

博主推荐

换一批

没有更多推荐了,返回首页