RestTemplate注入bean
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
/**
* 远程调用配置
* @author gw_liuzp 2021/5/26 17:03 */
@Configurable
public class RemoteConfig {
@LoadBalanced
@Bean
private RestTemplate restTemplate(RestTemplateBuilder builder){
return builder.build();
}
}
调用
import com.demo.api.dto.user.FindPasswordDTO;
import com.demo.infra.remote.invoke.IamInvokeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
@Service
public class IamInvokeServiceImpl implements IamInvokeService {
@Autowired
private RestTemplate restTemplate;
@Override
public ResponseEntity<String> findPasswordByPhone(FindPasswordDTO passwordDTO, String userType, String businessScope, String captchaKey, String captcha){
String serviceName = "hzero-iam";
String urlParam = String.format("userType=%s&businessScope=%s&captchaKey=%scaptcha=%s",userType,businessScope,captchaKey,captcha);
String url= String.format("http://%s/%s",serviceName,"/hzero/v1/users/find-password/phone?"+urlParam);
// 请求体
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
HttpEntity<FindPasswordDTO> request = new HttpEntity<>(passwordDTO,headers);
// url入参
// Map<String, String> uriVariables = new HashMap<>();
// uriVariables.put("userType",userType);
// uriVariables.put("businessScope",businessScope);
// uriVariables.put("captchaKey",captchaKey);
// uriVariables.put("captcha",captcha);
return restTemplate.exchange(url,HttpMethod.PUT,request,String.class);
}