RestTemplate使用方法

单独使用调用其他服务请求:

    public static void getRestTemplate(String urls) {
        RestTemplate restTemplate = new RestTemplate();
        MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
        map.add("appKey", "123456789");
        map.add("appSecret", "123456789");
        Map post = restTemplate.postForObject(urls, map, Map.class);
    }

单独使用时直接new RestTemplate();
传入参数使用MultiValueMap对象才可以,普通Map不行。

SpringCloud使用:

配置Bean

@Configuration
public class ConfigBean {//@Configuration  ==>  spring里的applicationContext.xml

    //配置负载均衡实现RestTemplate
    //IRle
    //RoundRobinRule  轮询
    //RandomRule  随机
    //AvailabilityFilteringRule: 会先过滤掉,跳闸,访问故障的服务,对剩下的进行轮询
    //RetryRule: 会先按照轮询获取服务,如果服务获取失败,则会在指定时间内进行重试
    @Bean
    @LoadBalanced //Ribbon
    public RestTemplate getRestTemplate(){
        return new RestTemplate();
    }

}

注入与使用:

@RestController
public class DeptConsumerController {

    //RestTemplate    供我们直接调用   注册到Spring中
    @Autowired
    private RestTemplate restTemplate;//提供多种便捷访问远程http服务的方法,简单的Restful服务模板~
    //方法参数 ==> (url,传入的参数:实体:map,返回类型:Class<T> responseType)

    //private static final String REST_URL_PREFIX="http://localhost:8001";
    //通过Ribbon,我们这里的地址,应该是一个变量,通过服务访问
    private static final String REST_URL_PREFIX="http://SPRINGCLOUD-PROVIDER-DEPT";
//    private static final String REST_URL_PREFIX="http://www.jinstudy.com:9527/jin/mydept";

    @RequestMapping("/consumer/dept/add")
    public boolean add(Dept dept){
        return restTemplate.postForObject(REST_URL_PREFIX+"/dept/add",dept,boolean.class);
    }
}

地址位置可以使用微服务定义的服务名 。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值