应用间通信RestTempate,Ribbon,Fegin

本文深入探讨了微服务架构下的应用间通信机制,对比了HTTP与RPC的不同,重点介绍了SpringCloud与Dubbo在微服务通信和服务治理方面的应用。同时,详细解析了RestTemplate的三种调用方式,以及如何通过Ribbon实现服务发现与负载均衡策略的定制。

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接口,调用

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值