springboot实现远程服务暴露与调用

本文介绍了如何在SpringBoot中实现远程服务的暴露和调用。服务端通过定义接口、实现接口和配置服务暴露来完成接口的发布。应用端则通过引入接口文件,配置远程调用,调用服务。关键点在于,对象参数需实现Serializable接口以确保序列化和反序列化的正确性。远程服务调用的原理可参考提供的时序图链接。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

pom引用

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>5.0.7</version>
        </dependency>

服务端暴露接口:

1、定义接口

public interface DemoInterface {
    BaseResponse get(QueryDTO dto);
}

2、接口实现类

@Slf4j
@Service
public class DemoInterfaceImpl implements DemoInterface {
      @Override
    public BaseResponse get(QueryDTO dto) {
    	return BaseResponse.success();
    }
}

3、配置服务暴露

@Configuration
public class RemotingConfig {

    @Resource
    private DemoInterface demoInterface;

    @Bean("/demoTest")
    public HttpInvokerServiceExporter elasticUserFacade() {
        HttpInvokerServiceExporter exporter = new HttpInvokerServiceExporter();
        exporter.setService(demoInterface);
        exporter.setServiceInterface(DemoInterface.class);
        return exporter;
    }
}

应用端调用:
1、引入相同的接口文件DemoInterface,可以用二方包的形式引入
2、配置远程调用

@Configuration
public class RemotingConfig {

    @Bean
    public HttpInvokerProxyFactoryBean demoInterfaceBean(){
        HttpInvokerProxyFactoryBean factoryBean = new HttpInvokerProxyFactoryBean();
        factoryBean.setServiceUrl( "http://www.test.com/demoTest");
        factoryBean.setServiceInterface(DemoInterface.class);
        factoryBean.setHttpInvokerRequestExecutor(httpComponentsHttpInvokerRequestExecutor());
        return factoryBean;
    }

    @Bean
    public HttpComponentsHttpInvokerRequestExecutor httpComponentsHttpInvokerRequestExecutor(){
        HttpComponentsHttpInvokerRequestExecutor executor = new HttpComponentsHttpInvokerRequestExecutor();
        return executor;
    }
}

3、服务调用

@Service
public class DemoManager {
    @Resource
    private DemoInterface demoInterface;
    
    public void get(String key) {
        demoInterface.get(new QueryDTO(key));
    }
}

注意:使用此种方式进行远程服务暴露,传递的参数如果是对象,需要实现Serializable接口,生成对应的serialVersionUID,因为参数传递的时候是转化成二进制的byte数据,在反序列化的时候需要根据UID确定唯一性,否则会报错

调用原理,时序图参考如下链接:
https://www.jianshu.com/p/6da39c67a586
https://my.oschina.net/u/2518341/blog/1800131

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值