温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

RMI spring

发布时间:2020-08-02 17:05:27 来源:网络 阅读:373 作者:乾坤刀 栏目:网络安全

1.业务接口类及其实现

/**
 * 定义一个远程接口
 */
public interface HelloService
{
    /**
     * 需要远程调用的方法
     * @param msg
     * @return
     */
    String sayHello(String msg);
}


public class HelloServiceImpl implements HelloService
{
    public String sayHello(String msg)
    {
        return "server received the msg : " + msg;
    }
}


2.RmiServiceExporter(服务端)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

    <!--RMI的服务实现类-->
    <bean id="helloService" class="com.rmi.spring.HelloServiceImpl" />

    <bean id="serviceExporter" class="org.springframework.remoting.rmi.RmiServiceExporter">
        <!--配置RMI的服务实现类-->
        <property name="service" ref="helloService" />
        <!--配置RMI的服务接口-->
        <property name="serviceInterface" value="com.rmi.spring.HelloService"/>
        <!--暴露的对外服务名-->
        <property name="serviceName" value="hello" />
        <!--服务本地注册端口-->
        <property name="registryPort" value="9123" />
        <!--服务对外暴露端口-->
        <property name="servicePort" value="9123" />
        <!--注册服务-->
        <property name="alwaysCreateRegistry" value="true" />
    </bean>

</beans>


3.RmiProxyFactoryBean(客户端)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

    <bean id="helloService" class="org.springframework.remoting.rmi.RmiProxyFactoryBean">
        <property name="serviceUrl" value="rmi://localhost:9123/hello" />
        <property name="serviceInterface" value="com.rmi.spring.HelloService"/>
    </bean>

</beans>


4.测试

public class HelloServer
{
    public static void main(String[] args)
    {
        new ClassPathXmlApplicationContext("spring-rmi-server.xml");
        System.err.println("rmi 服务启动!");
    }
}
public class HelloClient
{
    public static void main(String[] args)
    {
        ApplicationContext applicationContext 
        = new ClassPathXmlApplicationContext("spring-rmi-client.xml");

        HelloService helloService 
        = (HelloService)applicationContext.getBean("helloService");

        System.err.println(helloService.sayHello("测试测试!"));
    }
}


注:Registry服务的注册问题,有时会出现服务启动报错.


向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI