Spring Boot3远程调用工具RestClient

       Spring Boot3.2之后web模块提供了一个新的远程调用工具RestClient,它的使用比RestTemplate方便,开箱即用,不需要单独注入到容器之中,友好的rest风格调用。下面简单的介绍一下该工具的使用。

一、写几个rest风格测试接口


@RestController
@RequestMapping("/api")
public class RestApi {

    @PostMapping("/restTest")
    public String   testAdd(){
        return  System.currentTimeMillis() + " add success";
    }

    @PutMapping("/restTest")
    public String   testUpdate(){
        return  System.currentTimeMillis() + " update success";
    }

    @GetMapping("/restTest")
    public String   testGet(){
        return  System.currentTimeMillis() + " get success";
    }

    @DeleteMapping("/restTest")
    public String   testDel(){
        return  System.currentTimeMillis() + " del success";
    }
}

二、RestClinet调用增删改查接口

    private final static String  BASE_URI = "http://127.0.0.1:8081/api/restTest";

    public static void main(String[] args) {

        RestClient restClient = RestClient.create();

        ResponseEntity<String> postResponse = restClient.post().uri(BASE_URI).retrieve().toEntity(String.class);
        System.out.println("测试post接口  ===> "+ postResponse.getBody());

        ResponseEntity<String> putResponse = restClient.put().uri(BASE_URI).retrieve().toEntity(String.class);
        System.out.println("测试put接口   ===> "+ putResponse.getBody());

        ResponseEntity<String>   getResponse = restClient.post().uri(BASE_URI).retrieve().toEntity(String.class);
        System.out.println("测试get接口   ===> "+getResponse.getBody());

        ResponseEntity<String> delResponse = restClient.delete().uri(BASE_URI).retrieve().toEntity(String.class);
        System.out.println("测试del接口   ===> "+ delResponse.getBody());

    }

          

        使用简单方便,无论单体还是微服务,都可以轻松使用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值