Feign 服务调用

时间:2021-08-02
本文章向大家介绍Feign 服务调用,主要包括Feign 服务调用使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

两种服务调用方式

1,Feign
2,restTemplate

1. RestTemplate

1, application.yml

server:
  port: 8084
spring:
  application:
    name: feign-customer-example
  cloud:
    nacos:
      discovery:
        server-addr: 127.0.0.1:8848

2,在启动类中配置一个 bean

@Bean
@LoadBalanced//在注册中心里进行查找微服务,负载均衡
public RestTemplate restTemplate(){
    RestTemplate restTemplate=new RestTemplate();
    return  restTemplate;
}

3,使用 restTemplate 调用服务

package com.zgjt.controller;

import com.netflix.discovery.converters.Auto;
import com.zgjt.feign.FeignDemo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class EurakeTest {

    @Autowired
    private RestTemplate restTemplate;
    
    @RequestMapping("testRestTemplate")
    public void test(){
        restTemplate.getForEntity("http://EUREKA-CLIENT/eurakeTest",String.class);
    }
}

2. Feign 在 restTemplate 基础上做一次封装,定义和注册中心同样的接口,就可以调用注册中心的服务。

1,pom

<dependencies>
    <!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-feign -->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-openfeign</artifactId>
        <version>2.1.3.RELEASE</version>
    </dependency>
    <dependency>
        <groupId> com.alibaba.cloud</groupId>
        <artifactId> spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        <version>2.1.0.RELEASE</version>
    </dependency>
</dependencies>

2,application.yml

server:
  port: 8084
spring:
  application:
    name: feign-customer-example
  cloud:
    nacos:
      discovery:
        server-addr: 127.0.0.1:8848

3,定义 feign 接口

//注册到 nacos 的服务名
@FeignClient("nacos-provider-example")
@Component
public interface NacosProviderDemo {
      
    //方法签名要相同
    @PostMapping("/test")
    String helloNacos();
}

4,新建 controller 调用 feign

package com.zgjt.controller;

import com.zgjt.feign.NacosProviderDemo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class FeignTest {

    @Autowired
    private NacosProviderDemo feignDemo;

    @RequestMapping("/feignTest")
    public String test(){
        return feignDemo.helloNacos() ;
    }
}

5,启动类添加 @EnableFeignClients

package com.zgjt;

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

@SpringBootApplication
@EnableFeignClients
public class FeignCustomerApplication {

    public static void main(String[] args){
        SpringApplication.run(FeignCustomerApplication.class,args);
    }
}

负载均衡 Ribbon

ribbon 负载均衡策略,默认策略是轮询

Ribbon 自带负载均衡策略比较

给 restTemplate 添加负载均衡策略 @LoadBalanced
修改负载均衡策略,启动类中自定义一个 bean

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

@Configuration
public class ApplicationContentConfig {

    @Bean
    @LoadBalanced //开启ribbon自带负载均衡
    public RestTemplate getRestTemplate(){
        return new RestTemplate();
    }
      
    //修改轮询策略为随机
    @Bean
    public IRule myRule(){
        return new RandomRule();
    }
}

feign 已经集成了 ribbon,修改 feign 轮询策略, application.properties 中添加

EUREKA-CLIENT.ribbon.NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule

EUREKA-CLIENT 是提供者服务名

Ribbon 重试机制

当调用服务,超时未响应的时候,会根据配置重新调用服务

主要配置

ribbon:
  ReadTimeout: 1000
  ConnectTimeout: 1000
  MaxAutoRetries: 1 #同一台实例最大重试次数,不包括首次调用
  MaxAutoRetriesNextServer: 1 #重试负载均衡其他的实例最大重试次数,不包括首次调用
  OkToRetryOnAllOperations: false  #是否所有操作都重试

根据上面的参数计算重试的次数, 即重试3次 则一共产生4次调用

MaxAutoRetries + MaxAutoRetriesNextServer + ( MaxAutoRetries * MaxAutoRetriesNextServer )

另外, ribbon 默认重试一次, 读取数据时间为 1s

hystrix 熔断器

如果在 Ribbon 重试期间,时间超过了hystrix的超时时间,便会立即执行熔断,fallback。所以要根据上面配置的参数计算hystrix的超时时间,使得在重试期间不能达到hystrix的超时时间,不然重试机制就会没有意义

hystrix超时时间的计算:

(1 + MaxAutoRetries + MaxAutoRetriesNextServer) * ReadTimeout

hystrix 熔断机制使用

1,Pom

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

2,application.yml

#启动 hystrix
feign:
  hystrix:
    enabled: true

##请求进行重试
hystrix:
  command:
    Feign#test():
      execution:
        isolation:
          thread:
            timeoutInMilliseconds: 4000

3,重写 feign 方法

package com.zgjt.hystrix;

import com.zgjt.feign.FeignDemo;
import org.springframework.stereotype.Component;

@Component
public class HystrixDemo implements FeignDemo {
    @Override
    public String test() {
        System.out.println("hello hystrix");
        return "1";
    }
}

4,feign 接口声明调用失败使用的实现类,添加 fallback 参数

@FeignClient(name ="service-vod",fallback = VodClientRealize.class)
@Component
public interface VodClient {
    @PostMapping("/vod/videos/dropVideos")
    ResultApi dropVideos(@RequestBody String videoId);
}
给我一片天空,让我自由的飞翔;给我一片大地,让我自由的呼吸;人类需要一个共同的目标 众人拾柴,火焰高,发光,发亮,暖人心

原文地址:https://www.cnblogs.com/cnff/p/14344712.html