OpenFgein使用

消费者主启动类上:
@EnableFeignClients()
@SpringBootApplication
public class OrderfeignMain80 {
    public static void main(String[] args) {
        SpringApplication.run(OrderfeignMain80.class,args);
    }
}

 

调用服务的名称:
@Component
@FeignClient(value = "CLOUD-PAYMENT-SERVER")
public interface PaymentFeginService {
    @GetMapping("/payment/selectOne/{id}")
     CommonResult selectOne(@PathVariable(name = "id") Integer id);

    @GetMapping("/payment/timeOut")
     CommonResult timeOut();

    @GetMapping("/payment_timeOut/{id}")
    String payment_timeOut(@PathVariable("id") Integer id);

 

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>

 

OpenFegin超时与日志控制

 

package com.atguigu.springcloud.config;

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

import java.util.concurrent.TimeUnit;

/**
 * TODO
 *
 * @author wangbiao
 *
 * 日志级别:
NONE,
BASIC,
HEADERS,
FULL;
* @description 自定义日级别 * @date 2021/1/19 19:04 */ @Configuration public class FeignConfig { @Bean public Retryer feignRetryer() { return new Retryer.Default(100, TimeUnit.SECONDS.toMillis(1),3); } @Bean public Logger.Level feignLoggerLevel() { return Logger.Level.FULL; } } 配置指定那个包下的那个接口的级别:logging.level.com.atguigu.springcloud.config.FeignConfig=debug

 

OpenFegin调用默认是1秒钟调用,超时就报错

 

可配置参数:
# ribbon的可配置部分
#ribbon.ReadTimeout=1000 //处理请求的超时时间,默认为1秒
#ribbon.ConnectTimeout=1000 //连接建立的超时时长,默认1秒
#ribbon.MaxAutoRetries=1 //同一台实例的最大重试次数,但是不包括首次调用,默认为1次
#ribbon.MaxAutoRetriesNextServer=0 //重试负载均衡其他实例的最大重试次数,不包括首次调用,默认为0次
#ribbon.OkToRetryOnAllOperations=false //是否对所有操作都重试,默认false
## Feign的可配置部分
#feign.hystrix.enabled=false //Feign是否启用断路器,默认为false
#feign.client.config.default.connectTimeout=10000 //Feign的连接建立超时时间,默认为10秒
#feign.client.config.default.readTimeout=60000 //Feign的请求处理超时时间,默认为60
#feign.client.config.default.retryer=feign.Retryer.Default //Feign使用默认的超时配置,在该类源码中可见,默认单次请求最大时长1秒,重试5次

 

openfegin负载均衡策略:

 

负载均衡策略,默认实现的策略接口是IRule,Ribbon默认采用的是RoundRobinRule即轮询策略
改变方式有两种:
1.修改配置文件
2.修改消费者启动类或者定义一个配置类实现负载均衡策略的变更

  
(一)更换内置策略
若要更换负载均衡策略,则首先要了解负载均衡策略的定义接口IRule.。Ribbon默认采用的是RoundRobinRule,即轮询策略。但通过修改消费者工程的配置文件,或修改
消费者的启动类或JavaConfig类可以实现更换负载均衡策略的目的。
1、修改配置文件
修改配置文件,在其中添加如下内容,指定要使用的负载均衡策路<clientName>.<clientConfigNameSpace>.NFLoadBalancerRuleClassName。
该方式的好处是,可以为不同的微服务指定相应的负载均衡策略。

比如我的客户端是OrderConsumerService现在把他的负载均衡策略改为i随机
OrderConsumerService:
  ribbon:
    NFLoadBalancerRuleClassName:com.netflix.loadbalancer.RandomRule
2.建一个配置类,添加Bean方法,全局所有fegin对应的服务都可以生效
@Configurable
public class MySelfRule {
    @Bean
    public IRule myRule(){
        return  new RandomRule();//随机
    }
}
3.自定义负载均衡

/**
 * 测试自己写的轮询算法
 * @return
 */
public interface LoadBalancer {
    ServiceInstance instances(List<ServiceInstance> serviceInstances);
}


/**
 * 测试自己写的轮询算法  自定义负载算法过程
 * @return
 */
@Component
public class MyLB implements LoadBalancer {
    private AtomicInteger nextServerCyclicCounter=new AtomicInteger(0);
    public final int cas(){
        int current;
        int next;
        do{
             current=this.nextServerCyclicCounter.get();
             next=current>=2147483647?0:current+1;
        }while (!this.nextServerCyclicCounter.compareAndSet(current,next));
        System.out.println("****next:"+next);
        return next;
    }


导入使用:
 @Resource
    private LoadBalancer loadBalancer;

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



    /**
     * 测试自己写的轮询算法  多个服务实例名称要一样,这里是CLOUD-PAYMENT-SERVER
     * @return
     */
    @GetMapping("/consumer/lb")
    public String lb() {
        List<ServiceInstance> instances=discoveryClient.getInstances("CLOUD-PAYMENT-SERVER");
        if(instances==null||instances.size()<=0){
            return  null;
        }
        ServiceInstance serviceInstance=loadBalancer.instances(instances);
        URI uri=serviceInstance.getUri();
        return  restTemplate.getForObject(uri+"/payment/payment/lb",String.class);
    }

 

 

ribbon内置负载均衡:

 

Ribbon内置负载均衡算法
1、RoundRobinRule
轮询策略:Ribbon默认采用的策路。若经过一轮轮询没有找到可用的provider,.其最多轮询10轮(代码中写死的,不能修改)。若还未找到,
2、RandomRule
随机策略:从所有可用的provider中随机选择一个。
3、Retry Rule
重试策略:先按照RoundRobinRule策略获取server.,若获取失败,则在指定的时限内重试。默认的时限为500亳秒。
4、BestAvailableRule
最可用策略:选择并发量最小的provider,即连接的消费者数量最少的provider。其会遍历服务列表中的每一个server,选择当前连接数量
minimalConcurrentConnections最小的server.
5.AvailabilityFilteringRule
可用过滤算法:该算法规则是过滤掉处于熔断状态的server与已经超过连接极限的server,对剩余server采用轮询策路。

 

 

自定义实现负载均衡:

import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.RoundRobinRule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
 
@Configuration
public class CustomLoadBalancerConfiguration {
 
    @Bean
    public IRule randomRule() {
        return new RandomRule(); // 自定义的轮询策略
    }
 
}
 
class RandomRule extends RoundRobinRule {
    @Override
    public void initWithNiwsConfig(IClientConfig clientConfig) {
        // 初始化逻辑,如果需要的话
    }
 
    @Override
    public Server choose(ILoadBalancer lb, Object key) {
        if (lb == null) {
            return null;
        }
        Server server = null;
        while (server == null) {
            // 随机从服务器列表中选择一个
            List<Server> upList = lb.getReachableServers();
            List<Server> allList = lb.getAllServers();
            int serverCount = allList.size();
            if (serverCount == 0) {
                return null;
            }
            int index = new Random().nextInt(serverCount);
            server = upList.get(index);
            if (server == null) {
                Thread.yield();
            }
        }
        return server;
    }
}

  

 

四、负载均衡器SpringCloudLoadBalancer
由于Netflix对于Ribbon的维护已经暂停,所以Spring Cloud对于负载均衡建议使用由其自己定义的Spring Cloud LoadBalancer。对于Spring Cloud LoadBalancer的使
用非常简单。
1、关闭Ribbon的负载均衡器
spring:
application:
name:consumer01-depart
cloud:
loadbalancer:
#关闭Ribbong的负载均衔器
ribbon:
enabled:false
2、pom中添加LoadBalancerf依粒
<↓-spring cloud loadbalancer依赖-
<dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-openfeign</artifactId>
                <version>2.2.1.RELEASE</version>
            </dependency>

 

posted @ 2022-04-08 16:23  余生请多指教ANT  阅读(129)  评论(0)    收藏  举报