栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringCloud学习-第二节-服务负载与调用

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringCloud学习-第二节-服务负载与调用

一、Ribbon(负载均衡+RestTemplate) 1.概述

Spring Cloud Ribbon是基于Netflix Ribbon实现的一套客户端负载均衡的工具。

主要功能是提供客户端的软件负载均衡算法和服务调用。Ribbon客户端组件提供一系列完善的配置项如连接超时,重试等。简单的说,就是在配置文件中列出Load Balancer(简称LB)后面所有的机器,Ribbon会自动的帮助你基于某种规则(如简单轮询,随机连接等)去连接这些机器。我们很容易使用Ribbon实现自定义的负载均衡算法。

2.Ribbon工作流程

第一步先选择 EurekaServer ,它优先选择在同一个区域内负载较少的server.
第二步再根据用户指定的策略,在从server取到的服务注册列表中选择一个地址。
其中Ribbon提供了多种策略:比如轮询、随机和根据响应时间加权。

3.Ribbon的核心组件IRule
  • com.netflix.loadbalancer.RoundRobinRule:轮询
  • com.netflix.loadbalancer.RandomRule:随机
  • com.netflix.loadbalancer.RetryRule:先按照RoundRobinRule的策略获取服务,如果获取服务失败则在指定时间内会进行重试,获取可用的服务
  • WeightedResponseTimeRule:对RoundRobinRule的扩展,响应速度越快的实例选择权重越大,越容易被选择
  • BestAvailableRule:会先过滤掉由于多次访问故障而处于断路器跳闸状态的服务,然后选择一个并发量最小的服务
  • AvailabilityFilteringRule:先过滤掉故障实例,再选择并发较小的实例
  • ZoneAvoidanceRule:默认规则,复合判断server所在区域的性能和server的可用性选择服务器
4.Ribbon负载规则替换

(1)创建负载规则配置类
注意:该配置类不可以放在@ComponentScan所扫描的当前包下以及子包下,否则会被所有的Ribbon客户端所共享,达不到特殊化定制的目的

package com.zj.ribboncofig;

import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.RandomRule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


@Configuration
public class MyRibbonRule {
    @Bean
    public IRule randomRule(){
        return new RandomRule();
    }
}

(2)启动类添加@RibbonClient注解,name为要访问的服务名称,configuration为负载规则配置类

package com.zj.springcloud;

import com.zj.ribboncofig.MyRibbonRule;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.ribbon.RibbonClient;


@SpringBootApplication
@EnableEurekaClient
@RibbonClient(name = "SPRINGCLOUD-PAYMENT",configuration = MyRibbonRule.class)
public class OrderAppication {
    public static void main(String[] args) {
        SpringApplication.run(OrderAppication.class,args);
    }
}
5.自定义Ribbon负载规则(需关闭默认Ribbon规则)

(1)自定义规则

package com.zj.springcloud.myribbonrule;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;


@Component
public interface MyLoadBalanver {
    ServiceInstance instances(List serviceInstances);
}
package com.zj.springcloud.myribbonrule;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;


@Component
public class MyRibbonRule implements MyLoadBalanver{
    private AtomicInteger atomicInteger = new AtomicInteger(0);

    @Override
    public ServiceInstance instances(List serviceInstances)
    {
        int index = getAndIncrement() % serviceInstances.size();
        return serviceInstances.get(index);
    }

    public final int getAndIncrement()
    {
        int current;
        int next;
        do
        {
            current = this.atomicInteger.get();
            next = current >= 2147483647 ? 0 : current + 1;
        } while(!this.atomicInteger.compareAndSet(current, next));
        System.out.println("*****next: "+next);
        return next;
    }
}

(2)调用

@Autowired
private DiscoveryClient discoveryClient;
@Autowired
private MyLoadBalanver myLoadBalanver;
 @GetMapping("myribbonrule/{id}")
    public CommonResult myRibbonRule(@PathVariable("id") Long id){
        List instances = discoveryClient.getInstances("SPRINGCLOUD-PAYMENT");

        if(instances == null || instances.size()<=0) {
            return null;
        }

        ServiceInstance instances1 = myLoadBalanver.instances(instances);
        URI uri = instances1.getUri();
        log.info("服务器为:" + uri);
        String url = uri+"/payment/query/"+id;
        return restTemplate.getForObject(uri+"/payment/query/"+id,CommonResult.class);
    }
二、OpenFeign 1.概述

Feign是一个声明式的Web服务客户端,让编写Web服务客户端变得非常容易,只需创建一个接口并在接口上添加注解即可
Feign与OpenFeign的区别

FeignOpenFeign
Feign是Spring Cloud组件中的一个轻量级RESTful的HTTP服务客户端
Feign内置了Ribbon,用来做客户端负载均衡,去调用服务注册中心的服务。Feign的使用方式是:使用Feign的注解定义接口,调用这个接口,就可以调用服务注册中心的服务OpenFeign是Spring Cloud 在Feign的基础上支持了SpringMVC的注解,如@RequesMapping等等。OpenFeign的@FeignClient可以解析SpringMVC的@RequestMapping注解下的接口,并通过动态代理的方式产生实现类,实现类中做负载均衡并调用其他服务。
2.Feign使用步骤

(1)引入jar


	org.springframework.cloud
	spring-cloud-starter-openfeign

(2)启动类添加@EnableFeignClients

package com.zj.springcloud;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;


@SpringBootApplication
@EnableFeignClients
public class OrderFeignApplication {
    public static void main(String[] args) {
        SpringApplication.run(OrderFeignApplication.class,args);
    }
}

(3)fegin接口

package com.zj.springcloud.fegin;

import com.zj.springcloud.common.CommonResult;
import com.zj.springcloud.entity.Payment;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;


@Component
@FeignClient(value = "SPRINGCLOUD-PAYMENT")
public interface PaymentFeignService {
    @GetMapping("/payment/query/{id}")
    CommonResult getPaymentById(@PathVariable("id") Long id);
}

(4)调用

package com.zj.springcloud.controller;

import com.zj.springcloud.common.CommonResult;
import com.zj.springcloud.entity.Payment;
import com.zj.springcloud.fegin.PaymentFeignService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;


@RestController
public class OrderFeignController {
    @Autowired
    private PaymentFeignService paymentFeignService;

    @GetMapping("/consumer/payment/query/{id}")
    public CommonResult getPaymentById(@PathVariable("id") Long id){
        return paymentFeignService.getPaymentById(id);
    }
}

(3)Feign超时控制

#设置feign客户端超时时间(OpenFeign默认支持ribbon)
ribbon:
#指的是建立连接所用的时间,适用于网络状况正常的情况下,两端连接所用的时间
  ReadTimeout: 5000
#指的是建立连接后从服务器读取到可用资源所用的时间
  ConnectTimeout: 5000
3.Feign日志级别设置

(1)方式一:配置文件

logging:
  level:
    # feign日志以什么级别监控哪个接口
    com.atguigu.springcloud.service.PaymentFeignService: debug

(2)方式二:配置类

package com.zj.springcloud;

import feign.Logger;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


@Configuration
public class FeignConfig {
    @Bean
    Logger.Level feignLoggerLever(){
        return Logger.Level.FULL;
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/667526.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号