1.应用间通信
HTTP VS RPC
Spring Cloud:微服务下的一站式解决方案。服务间使用HTTP RESTFUL通信。Spring Cloud中服务间两种restful调用方式RestTemplate和Fegin。
Dubbo:提供了服务注册发现,负载均衡,路由,服务治理和监控可视化平台
2.RestTemplate的三种调用方式
1.第一种方式:
@GetMapping("/getProductMsg")
public String getProductMsg() {
RestTemplate restTemplate=new RestTemplate();
String response = restTemplate.getForObject("http://localhost:8080/msg", String.class);
return response;
}
2.第二种方式:
@Autowired
private LoadBalancerClient loadBalancerClient;
@GetMapping("/getProductMsg")
public String getProductMsg() {
ServiceInstance serviceInstance = loadBalancerClient.choose("product");
String url = String.format("http://%s:%s/msg", serviceInstance.getHost(), serviceInstance.getPort());
RestTemplate restTemplate=new RestTemplate();
String response = restTemplate.getForObject(url, String.class);
return response;
}
3.第三种方式:
@Component
public class RestTemplateConfig {
@Bean
@LoadBalanced
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
@Autowired
private RestTemplate restTemplate;
@GetMapping("/getProductMsg")
public String getProductMsg() {
String response = restTemplate.getForObject("http://product/msg", String.class);
return response;
}
3.Ribbon
1.服务发现:ServerList
服务选择规则:IRule
服务监听(检测失效服务,做到高效剔除):ServerListFilter
2.修改负载均衡策略
@Configuration
public class MyRuleConfig {
@Bean
public IRule iRule(){
return new RandomRule();
}
}
4.Fegin
声明式REST客户端(伪RPC)
采用基于接口的注解
1.调用方导入依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
2.调用方主类加注解@EnableFeignClients
3.调用方编写接口
@FeignClient(name = "product")
public interface ProductClient {
@GetMapping("/msg")
String productMsg();
}
4.注入ProductClient接口,调用
本文深入探讨了微服务架构下的应用间通信机制,对比了HTTP与RPC的不同,重点介绍了SpringCloud与Dubbo在微服务通信和服务治理方面的应用。同时,详细解析了RestTemplate的三种调用方式,以及如何通过Ribbon实现服务发现与负载均衡策略的定制。
168万+

被折叠的 条评论
为什么被折叠?



