一、总述
在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。
相关推荐
在“Flex + Hessian 学习笔记(二)”中,我们可能涉及以下知识点: 1. **Flex应用的架构**:Flex应用通常包含三层结构:表现层(Presentation)、业务逻辑层(Business Logic)和数据访问层(Data Access)。Hessian...
Hessian学习笔记 Hessian是一种基于Binary-RPC协议实现的远程通讯library,由Caucho提供。下面是Hessian的学习笔记: 一、简介 Hessian是基于Binary-RPC协议实现的远程通讯library,用于实现远程过程调用(RPC)...
**WebService的轻量级实现——Hessian学习笔记** 在IT行业中,WebService作为一种常见的跨平台、跨语言的通信机制,被广泛应用于系统间的交互。然而,传统的SOAP(Simple Object Access Protocol)协议实现的...
本篇文章将深入探讨“java后端学习笔记”中的关键知识点,包括消息队列(Message Queuing)服务如ActiveMQ和RabbitMQ、工作流引擎Activity、容器化技术Docker、分布式服务框架Dubbo、网络库Netty、RPC(Remote ...
《MyDubbo:Dubbo源码学习笔记》 在Java开发领域,Dubbo是一个非常知名的分布式服务框架,它由阿里巴巴开源并广泛应用于大型企业系统。本篇笔记将深入探讨Dubbo的核心概念、工作原理以及源码解析,帮助开发者更好地...
### SpringCloud微服务基础知识解析 #### 一、项目架构演进概述 在现代软件开发过程中,随着业务复杂度和技术...然而,微服务也带来了诸如服务治理、数据一致性等新的挑战,这需要开发者在实际应用中持续学习和探索。
1. **Protocol组件**:Dubbo的协议层负责序列化、反序列化以及网络通信,例如Dubbo协议、RMI协议、Hessian2协议等,这些都是Dubbo实现高效RPC的核心部分。 2. **Registry组件**:服务注册与发现的实现,包括...
两者之间通过Dubbo的RPC(Remote Procedure Call)机制进行通信。 2. **服务注册与发现** Dubbo支持多种注册中心,如Zookeeper、Eureka等,用于存储服务提供者的信息。服务消费者通过注册中心查找并订阅所需的服务...
6. **远程调用(RPC)**:Dubbo使用了基于Netty的异步高性能通信框架,支持多种RPC协议,如Dubbo协议、HTTP、Hessian等。在这个教程中,我们将看到如何通过Dubbo的RPC机制进行服务间的远程调用。 7. **服务治理**:...