springCloud(13)-Ribbon-consumer-负载均衡-@RibbonClient -RestTemplate

Ribbon 是干什么的,做负载均衡的。
有很多个providers,consumer调用哪个provider?根据特点算法从服务列表中选取一个要访问的服务。

consumer端的实现 consumer : 需要支持可设定算法的负载均衡功能 要改3个地方。
下面以order80为例
1.添加依赖:
2.controller +-RestTemplate
3.负载均衡策略的设定

 


1.添加依赖:
 

 <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>


2.controller +-RestTemplate
2.1 RestTemplate 的使用不是直接Importclass 是需要写config配置类的
 

@Configuration
public class ApplicationContextConfig
{
    @Bean
    @LoadBalanced
    public RestTemplate getRestTemplate()
    {
        return new RestTemplate();
    }
}


2.2 RestTemplate在Controller里被调用

 @Resource
    private RestTemplate restTemplate;

    //post
    @GetMapping("/consumer/payment/create")
    public CommonResult<Payment> create(Payment payment) {
        return restTemplate.postForObject(PAYMENT_URL + "/payment/create", payment, CommonResult.class);
    }

    //getObject  返回的是 响应体
    @GetMapping("/consumer/payment/get/{id}")
    public CommonResult<Payment> getPayment(@PathVariable("id") Long id) {
        return restTemplate.getForObject(PAYMENT_URL + "/payment/get/" + id, CommonResult.class);
    }

    //getEntity 返回的是 响应头、状态码、响应体
    @GetMapping("/consumer/payment/getForEntity/{id}")
    public CommonResult<Payment> getPayment2(@PathVariable("id") Long id)
    {
        ResponseEntity<CommonResult> entity = restTemplate.getForEntity(PAYMENT_URL+"/payment/get/"+id,CommonResult.class);

        if(entity.getStatusCode().is2xxSuccessful()){
            return entity.getBody();
        }else{
            return new CommonResult<>(444,"操作失败");
        }
    }


3.负载均衡策略的设定

实现步骤:
3.1分包建类 @configuration @Bean
Rebbion的包不能放在@ComponentScan下

@Configuration
public class MySelfRule {
    @Bean
    public IRule myRule()
    {
        return  new RandomRule();//定义为随机

    }
}


3.2 主类添加@RibbonClient  
@RibbonClient(name = "CLOUD-PAYMENT-SERVICE",configuration= MySelfRule.class)

@SpringBootApplication
@EnableEurekaClient
@RibbonClient(name = "CLOUD-PAYMENT-SERVICE",configuration= MySelfRule.class)
public class OrderMain80
{
    public static void main(String[] args) {
            SpringApplication.run(OrderMain80.class, args);
    }
}


3.3 测试
http://localhost/consumer/payment/get/1
8001 8002 端口将随机出现,以前是顺序出现。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值