Spring-RMI远程接口调用简单配置

远程调用RMI(Remote Method Invocation): 经过使用RmiProxyFactoryBean 和 RmiServiceExporter,而且,Spring支持两个传统的RMI(使用 java.rmi.Remote接口和java.rmi.RemoteException)和经过RMI调用器实现的暴露远程调用(支持任何Java接口)。java

RMI远程访问基本流程

    1). 服务端定义远程访问接口;spring

    2). 服务端经过RmiServiceExporter暴露服务接口缓存

    3). 客户端定义与服务端已暴露的相同接口服务器

    4). 客户端经过RmiProxyFactoryBean调用服务接口app

1.客户端配置三步:ide

1)applicationContext.xml测试

 <!-- spring rmi远程接口调用  客户端调用-->
     <bean id="clientRmi" class="org.springframework.remoting.rmi.RmiProxyFactoryBean">
        <property name="serviceUrl" value="rmi://localhost:1199/userRmiService"></property> 
        <property name="serviceInterface" value="com.maystar.common.service.RmiUserService"></property> 
        <!-- 注意:若是以下两项不配置,当服务器未开启,客户端没法打包,会有拒绝链接异常。 -->
        <!-- 预查找远程对象 默认为true -->
        <property name="lookupStubOnStartup" value="false"></property>
        <!-- 是否刷新远程调用缓存的stub -->
        <property name="refreshStubOnConnectFailure" value="true"></property>
    </bean>spa

2)接口:.net

public interface RmiUserService {
    User getUserByAcount(String name,String password);
    
    void insert(User user);
}xml

3)调用

//测试rmi远程接口调用代码
        System.out.println("rmi客户端开始调用");
        RmiUserService rmiUserService=(RmiUserService)SpringContextUtil.getBean("clientRmi");
        User list=(User)rmiUserService.getUserByAcount("张三", ":张三的密码");//spring实现反序列化
        System.out.println(list);
        System.out.println("rmi客户端调用结束");

 

2.服务器端配置

1)applicationContext.xml

<!-- spring rmi远程接口调用 服务端配置-->
    <bean name="rmiService" class="com.maystar.common.service.UserRmiServiceImpl"/>
    <bean  class="org.springframework.remoting.rmi.RmiServiceExporter">
       <!-- RMI服务名称,可自定义服务名称 -->
       <property name="serviceName" value="userRmiService" ></property>
        <!-- 导出实体 -->
       <property name="service" ref="rmiService" ></property>
       <property name="serviceInterface" value="com.maystar.common.service.RmiUserService"></property>
       <property name="registryPort" value="1199" ></property>
    </bean>

2)接口(同客户端一致)

public interface RmiUserService {
    User getUserByAcount(String name,String password);
    
    void insert(User user);
}

3)接口实现类

public class UserRmiServiceImpl implements RmiUserService{
    @Override
    public User getUserByAcount(String name, String password) {
       System.out.println("服务端获取用户信息:" + name + password);
       User user=new User();
       user.setUsername(name);
       user.setPassword(password);
       return user;
    }
    @Override
    public void insert(User user) {
       System.out.println("开始插入用户信息:" + user.toString());
    }
}

输出结果:

rmi客户端开始调用 张三 :张三的密码 rmi客户端调用结束

相关文章
相关标签/搜索