使用的是mybatis-plus完成CRUD
- 配置类:
/**
* @author:
* RestTemplate工具类,主要用来提供RestTemplate对象
*/
@Configuration//加上这个注解作用,可以被Spring扫描
public class RestTemplateConfig {
/**
* 创建RestTemplate对象,将RestTemplate对象的生命周期的管理交给Spring
*
* @return
*/
@Bean
public RestTemplate add() {
RestTemplate restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory());
restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));//支持中文编码
return restTemplate;
}
}
- controller类 这里只介绍比较常用的两个调用方法 id详情查询 ,添加
@Resource
private RestTemplate restTemplate;
//远程添加方法
@GetMapping("/add")
public void add(Supplier supplier) {
supplierService.save(supplier);
}
/**
* 调用远程添加方法 url 远程的添加路径
* @param suppQuery
* @return
*/
@PostMapping("/restTemplate/add")
public ResponseEntity<String> add(SuppQuery suppQuery) {
ResponseEntity<String> entity = restTemplate.postForEntity("http://localhost:8088/add", suppQuery, String.class);
System.out.println("suppQuery = " + suppQuery);
return entity;
}
//SuppQuery类 是远程要添加的javabean
@Data
//封装对象
public class SuppQuery {
private String gid;
private String name;
private String customEmail;
}
- 根据id查询 远程调用
//远程端接口
@GetMapping("/detail/{id}")
public Supplier findAll2(@PathVariable("id") String gid) {
Supplier byId = supplierService.getById(gid);
return byId;
}
//调用远程接口
@GetMapping(value = "/restTemplate/{gid}")
public void download(@PathVariable("gid") String gid) throws IOException {
//訪問url + token
String url1 = "http://localhost:8088/detail/" + gid;
//远程请求
SuppQuery forObject = restTemplate.getForObject(url1, SuppQuery.class);
System.out.println("远程user数据 = " + forObject);
String customName = forObject.getCustomName();
System.out.println("customName = " + customName);
}