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);
}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

雾林小妖

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值