微服务模块之间接口调用方式(RestTemplate )
RestTemplate 是org.springframework.web.client包下面的类,可以实现Post、Get等请求
配置类,配置RestTemplate Bean
@Configuration
public class RestTemplateConfig {
@Bean
@LoadBalanced
public RestTemplate
restTemplate(ClientHttpRequestFactory factory
) {
return new RestTemplate(factory
);
}
@Bean
public ClientHttpRequestFactory
simpleClientHttpRequestFactory() {
SimpleClientHttpRequestFactory factory
= new SimpleClientHttpRequestFactory();
factory
.setReadTimeout(5000);
factory
.setConnectTimeout(5000);
return factory
;
}
}
注入RestTemplate 使用RestTemplate 调用接口
Url格式:http://Eruake注册的服务名/接口地址
@RequestMapping("/test2")
public void test2(){
try {
String url
= "http://oscoreserver/test/test1";
Map
<String, Object> parameters
= new HashMap<>(4);
parameters
.put("grant_type", "client_credential");
Object object
= restTemplate
.postForObject(url
, parameters
, String
.class);
System
.out
.println(object
);
}catch (Exception e
){
logger
.info(e
.getMessage());
e
.printStackTrace();
}
}
RestTemplate Post请求
使用postForObject请求接口
String url
= "http://oscoreserver/test/test1";
Map
<String, Object> parameters
= new HashMap<>(4);
parameters
.put("tagid", "6666");
Object object
= restTemplate
.postForObject(url
, parameters
, String
.class);
postForObject()
public <T> T
postForObject(String url
, @Nullable Object request
, Class
<T> responseType
, Object
... uriVariables
) throws RestClientException
{}
public <T> T
postForObject(String url
, @Nullable Object request
, Class
<T> responseType
, Map
<String
, ?> uriVariables
) throws RestClientException
{}
public <T> T
postForObject(URI url
, @Nullable Object request
, Class
<T> responseType
) throws RestClientException
{}
postForEntity()
<T> ResponseEntity
<T> postForEntity(String var1
, @Nullable Object var2
, Class
<T> var3
, Object
... var4
) throws RestClientException
;
<T> ResponseEntity
<T> postForEntity(String var1
, @Nullable Object var2
, Class
<T> var3
, Map
<String
, ?> var4
) throws RestClientException
;
<T> ResponseEntity
<T> postForEntity(URI var1
, @Nullable Object var2
, Class
<T> var3
) throws RestClientException
;
RestTemplate Get请求
使用getForObject请求接口
Map
<String, Object> parameters
= new HashMap<>(4);
parameters
.put("tagid", "6666");
String result1
= restTemplate
.getForObject(url
, String
.class, paramMap
);
System
.out
.println("result1====================" + result1
);
getForObject()
public <T> T
getForObject(String url
, Class
<T> responseType
, Object
... uriVariables
){}
public <T> T
getForObject(String url
, Class
<T> responseType
, Map
<String
, ?> uriVariables
)
public <T> T
getForObject(URI url
, Class
<T> responseType
)
getForEntity()
public <T> ResponseEntity
<T> getForEntity(String url
, Class
<T> responseType
, Object
... uriVariables
){}
public <T> ResponseEntity
<T> getForEntity(String url
, Class
<T> responseType
, Map
<String
, ?> uriVariables
){}
public <T> ResponseEntity
<T> getForEntity(URI url
, Class
<T> responseType
){}