单独使用调用其他服务请求:
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);
}
}
地址位置可以使用微服务定义的服务名 。