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());}
使用简单方便,无论单体还是微服务,都可以轻松使用。