目 录CONTENT

文章目录

RestTemplate调用服务接口的一点学习

在水一方
2021-12-06 / 0 评论 / 0 点赞 / 951 阅读 / 1,921 字 / 正在检测是否收录...

java请求网络资源通常用HttpClient等,Spring封装了库,提供更为简洁的资源请求方式RestTemplate,RestTemplate 是从 Spring3.0 开始支持的一个 HTTP 请求工具

Spring注入方式使用

@Configuration  
public class RestClientConfig {  
  
    @Bean  
    public RestTemplate restTemplate() {  
        RestTemplate restTemplate = new RestTemplate();
        return restTemplate;  
    }  
  
}  

用到的时候注入一下

@Service
public class MntReqServiceImpl {
    @Autowired
    private RestTemplate restTemplate;

}

RestTemplate中的方法(了解发不同请求的方式对应的方法):

  • getForObject: 发送get请求,结果封装为指定对象。 提供class指定
  • getForEntity: 发送get请求,结果为Entity类型。
  • postForObject: 发送post请求,结果封装为指定对象
  • put:
  • delete:
  • exchange:通用执行方法
   @Override
    public R getReportData(String reportName, String workId) {
        String url = "http://XX.XX.XX.XX:8002/pcep-ems-ei-mnt/data/getMntRptModelDatas?rptReportName=1+&workId="+workId;
        R data = restTemplate.getForObject(url,R.class);
        return data;
    }

扩展:

使用RestTemplate来向服务的某个具体实例发起HTTP请求,但是具体的请求路径是通过拼接完成的,对于开发体验并不好。但是,实际上,在Spring Cloud中对RestTemplate做了增强,只需要稍加配置,就能简化之前的调用方式。

@EnableDiscoveryClient
@SpringBootApplication
public class TestApplication {

    public static void main(String[] args) {
        SpringApplication.run(TestApplication.class, args);
    }

    @Slf4j
    @RestController
    static class TestController {

        @Autowired
        RestTemplate restTemplate;

        @GetMapping("/test")
        public String test() {
            String result = restTemplate.getForObject("http://alibaba-nacos-discovery-server/hello?name=didi", String.class);
            return "Return : " + result;
        }
    }

    @Bean
    @LoadBalanced
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }

}

可以看到,在定义RestTemplate的时候,增加了@LoadBalanced注解,而在真正调用服务接口的时候,原来host部分是通过手工拼接ip和端口的,直接采用服务名的时候来写请求路径即可。在真正调用的时候,Spring Cloud会将请求拦截下来,然后通过负载均衡器选出节点,并替换服务名部分为具体的ip和端口,从而实现基于服务名的负载均衡调用。

使用exchange的方式来调用


  ResponseEntity<String> entity = restTemplate.exchange("http://open.api.tianyancha.com/services/open/search/2.0?word=" + word + "&pageSize=" + pageSize + "&pageNum=" + pageNum, HttpMethod.GET, getHttpHeaders(), String.class);
  JSONObject jsonObject = JSON.parseObject(entity.getBody());
  return R.succeed(jsonObject);

0

评论区