码迷,mamicode.com
首页 > 编程语言 > 详细

Spring对远程服务的支持

时间:2014-12-30 23:31:49      阅读:312      评论:0      收藏:0      [点我收藏+]

标签:

  Java程序有以下的远程调用技术选择:

技术分享

远程过程调用(RPC)是同步的,客户端在服务器端返回结果之前将一直被阻塞。

各种技术适用的场景如下:

技术分享

  典型的RMI开发的过程如下:

  1. 定义一个接口,用于客户端和服务器端的交互,接口要继承Remote接口,所有方法都要抛出RemoteException
  2. 编写服务器端的实现,实现第一步所编写的接口。
  3. 编写一个注册类,基于某个某个IP和端口(默认是1099)注册服务器端类的实现。
  4. 编写客户端的调用,基于IP,端口和注册的名称查找服务器端对应的类。
  5. RMI支持传递对象,要求对象实现Serializable接口。

 

  下面是Spring对RMI的支持,配置也很简单:

  一:服务器端

   1. 要暴露的服务的接口:

package com.excellence.webservice;

import java.util.List;

public interface AccountService {
    public void insertAccount(Account account);
    public List getAccounts(String name);
}

  

  2. 实现了该接口的类:

package com.excellence.webservice;

import java.util.List;

public class AccountServiceImpl implements AccountService {

    public void insertAccount(Account account) {
        System.out.println("inser!");
    }

    public List getAccounts(String name) {
        System.out.println("get");
        return null;
    }
}

  

  3. 在配置文件中公布改接口为RMI

<bean id="accountService" class="com.excellence.webservice.AccountServiceImpl" />
<bean name="service" class="org.springframework.remoting.rmi.RmiServiceExporter">
    <property name="serviceName" value="AccountService" ></property>
    <property name="service" ref="accountService"></property>
    <property name="serviceInterface"          value="com.excellence.webservice.AccountService"></property>
    <property name="registryPort" value="1199"></property>
</bean>

 

  4. 运行该RMI:

public class Demo {

public static void main(String[] args) {
    ApplicationContext ctx = new FileSystemXmlApplicationContext ("classpath:applicationContext.xml");
    RmiServiceExporter obj = (RmiServiceExporter)ctx.getBean("service");
    }
}

 

  二、客户端

  1.在配置文件中进行配置:

<bean id="accClient" class="org.springframework.remoting.rmi.RmiProxyFactoryBean">
    <property name="serviceUrl" value="rmi://localhost:1199/AccountService"></property>
    <property name="serviceInterface"     value="com.excellence.webservice.AccountService"></property>
</bean>

  2.调用RMI的方法:

public static void main(String[] args) {
    ApplicationContext ctx = new FileSystemXmlApplicationContext    ("classpath:applicationContext.xml");
    AccountService service = (AccountService)ctx.getBean("accClient");
    service.insertAccount(new Account());
    service.getAccounts("dd");
}

 

 

 

 

 

 

 

 

 

 

 

 

Spring对远程服务的支持

标签:

原文地址:http://www.cnblogs.com/lnlvinso/p/4194762.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!