RestTemplate调用其他微服务

 

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); 

} 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值