SpringCloud 服务之间的调用以及负载均衡
RestTemplate
服务间的调用就是在子模块间的相互调用;
在auth 模块中 调用demo中的有关方法;
在demo中创建一个借口
在auth中,创建一个RestTemplate 对象,调用
getForObject(“http://服务名/路径”,返回的类型,传递参数的类或map)
@GetMapping("/yuancheng")
public String yuancheng(){
RestTemplate restTemplate = new RestTemplate();
String response = restTemplate.getForObject("http://demo/clientMsg",String.class);
return response;
}
然后访问 /yuancheng
调用成功 ,返回 “111”
除了getForObject 还有postForObject 用法相同
put 与 delete 请求的方式,没有返回的参数
例如:
restTemplate.put(“http://HELLO-SERVICE/getbook3”, book, 99);
restTemplate.delete(“http://HELLO-SERVICE/getbook4”, 100);
get请求传参
需要加入占位符,传map
Map<String,String> map = new HashMap<String,String>();
map.put("str","hello");
String response = restTemplate.getForObject("http://demo/clientMsg/?str={str}",String.class,map);
return response;
接收参数
@GetMapping("/clientMsg")
public String clientMsg(@RequestParam Map<String,String> map){
return "222:"+map.get("str");
}
post传参
Map<String,String> map = new HashMap<String,String>();
map.put("str","hello");
String response = restTemplate.postForObject("http://demo/postTest",map,String.class);
return response;
@PostMapping("/postTest")
public String postTest(@RequestBody Map<String,String> map){
return "111:"+map.get("str");
}
负载均衡
在auth中新建一个配置类
使用@LoadBalanced 注解 ,表示开启客户端负载均衡。
@Configuration
public class RestConfig {
@Bean
@LoadBalanced
public RestTemplate getRestTemplate(){
return new RestTemplate();
}
}
@RestController
public class TestController {
@Autowired
private RestTemplate restTemplate;
@GetMapping("/yuancheng")
public String yuancheng(){
// RestTemplate restTemplate = new RestTemplate();
String response = restTemplate.getForObject("http://demo/clientMsg",String.class);
return response;
}
}
复制相同的demo子模块,更改不同的端口启动;
同样访问接口
第一次访问
第二次访问