springboot实现跨服务调用/springboot调用另一台机器上的服务

1、问题描述?

在实际的开发中,我们可能需要调用另一台服务器上的api服务,实现两台服务器之间的数据交互。

这个时候我们就可以使用springboot框架中提供的RestTemplate类实现。

其他如webClient或微服务中的feign等本文不做阐述。

使用起来相对简单。

2、RestTemplate使用详情。

2.1、创建springboot工程添加依赖包

RestTemplate相关依赖包在spring-boot-starter-web依赖包中。

复制代码
<!-- pom.xml -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

2.2、创建初始化RestTemplate配置类

1、此处创建RestTemplate有两种方式,一种是通过new方式直接创建,一种是通过builer方式在创建的时候提供更加详细的配置,如超时时间等。

2、二者创建略有不同,但是使用方式相同。

【第一种创建方式】

通过new RestTemplate();方式直接创建

复制代码
@Configuration
public class RestTemplateConfig {
    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
}

【第二种创建方式】

通过builder方式创建,提供更加详细的创建方式

复制代码
@Configuration
public class RestTemplateConfig {

    @Bean
    public RestTemplate restTemplate(RestTemplateBuilder builder) {
        // 使用builder链式调用设置不同的属性
        return builder
                //.additionalMessageConverters(new StringHttpMessageConverter()) // 添加消息转换器
                .setConnectTimeout(Duration.ofSeconds(5)) // 设置连接超时时间
                .setReadTimeout(Duration.ofSeconds(5)) // 设置读取超时时间
                .build(); // 构建RestTemplate实例
    }
}

2.3、使用RestTemplate调用远程api

【1、返回字符串类型的参数】

restTemplate.getForObject(url,String.class);返回字符串类型的结果。

复制代码
@Controller
public class TestController{
     @Autowired
     private RestTemplate restTemplate;
     
     @RequestMapping("/classRemoteApi")
     public String callRemoteApi(){
         String ur"http://172.33.20.101:8080/api";
         String result=restTemplate.getForObject(url,String.class);
         return result;
     } 
}

【2、返回更加详细的返回值信息】

restTemplate.getForEntity(url, String.class); 获取请求状态码、响应头等信息。

复制代码
public ResponseEntity<String> callRemoteApiWithResponseEntity() {
    String url = "http://example.com/api/data"; // 远程接口URL
    try {
        return restTemplate.getForEntity(url, String.class); 

    } catch (Exception e) {
        // 处理异常情况
        System.err.println("Error: " + e.getMessage());
    }
    return null;
}

【3、发送post等其他请求】

服务的api可能是post,put,delete等请求类型,可以使用如下方式进行操作

复制代码
public String postData(String url, Object requestBody) {
    HttpHeaders headers = new HttpHeaders();
    //配置数据交互类型为JSON
    headers.setContentType(MediaType.APPLICATION_JSON); 
    //HttpEntity存储请求头和请求体信息
    HttpEntity<Object> entity = new HttpEntity<>(requestBody, headers); 
    return restTemplate.postForObject(url, entity, String.class);
}
相关推荐
我命由我1234531 分钟前
执行 Gradle 指令报错,无法将“grep”项识别为 cmdlet、函数、脚本文件或可运行程序的名称
android·java·java-ee·android studio·android jetpack·android-studio·android runtime
考虑考虑44 分钟前
Sentinel安装
java·后端·微服务
IT_陈寒1 小时前
SpringBoot自动配置失灵?你可能忘了这个关键注解
前端·人工智能·后端
碎碎念_4921 小时前
SpringBoot + Vue 前后端分离从 0 到 1 完整环境配置流程
vue.js·spring boot·后端
逝水无殇1 小时前
C# 文件的输入与输出详解
开发语言·数据库·后端·c#
YIAN1 小时前
从手写 Agent 工具到 MCP 协议:一文搞懂大模型跨进程跨语言工具调用
后端·agent·mcp
小兔崽子去哪了2 小时前
Docker 删除镜像后磁盘空间没有释放?
后端·docker·容器
凤凰院凶涛QAQ2 小时前
《Java版数据结构 & 集合类剖析》栈与队列:“push/pop 是栈的灵魂,offer/poll 是队列的骨架——四组 API,两种人生”
java·开发语言·数据结构
高明珠2 小时前
麒麟 V10 SP1 排查实录:ttyS5 每 10 秒莫名收到一批报文,元凶是 eGTouchD
后端
卷无止境2 小时前
Python FFI 技术深度解析:ctypes、cffi 与 pybind11 的性能差异与实践挑战
后端·python