SpringCloud微服务服务间调用之OpenFeign介绍

开发微服务,免不了需要服务间调用。Spring Cloud框架提供了RestTemplate和FeignClient两个方式完成服务间调用,本文简要介绍如何使用OpenFeign完成服务间调用。

OpenFeign思维导图

在此奉上我整理的OpenFeign相关的知识点思维导图。

基础配置使用例子

(1)服务端:

@RestController
@RequestMapping("hello")
public class HelloController implements HelloApi {
    @Override
    public String hello(String name) {
        return "Hello, "+name+"!";
    }
}

API声明:

public interface HelloApi {

    @GetMapping("/hello/{name}")
    String hello(@PathVariable("name") String name);

    @GetMapping("/bye/{name}")
    ResponseValue<String> bye(@PathVariable("name") String name);

    @GetMapping(value = "/download")
    byte[] download(HttpServletResponse response);
}

(2)客户端:

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

开启配置 @EnableFeignClients,调用服务的代码:

@FeignClient(name="hello1", url = "127.0.0.1:8080", path = "hello")
public interface HelloApiExp extends HelloApi {
    @GetMapping("/download")
    Response download();
}

调用时的代码:

@RestController
@RequestMapping("client")
public class HelloClient {

    @Autowired
    private HelloApiExp helloApi;

    @GetMapping("/hello/{name}")
    public String hello(@PathVariable("name") String name){
        return helloApi.hello(name);
    }
}    

浏览器访问URL:http://127.0.0.1:8080/client/hello/Mark,页面返回: Hello, Mark!

@FeignClient的简单用法

属性名称 属性说明 默认值
name/value 作为serviceId,bean name
contextId 作为bean name,代替name/value的值
qualifier 限定词
url http的URL前缀(不包括协议名):主机名和端口号
decode404 请求遇到404则抛出FeignExceptions false
path 服务前缀,等同于ContextPath
primary whether to mark the feign proxy as a primary bean true

高级配置——使用configuration配置类

通过自定义配置类统一配置Feign的各种功能属性,FeignClientsConfiguration为默认配置:

@FeignClient(name="hello1", url = "127.0.0.1:8080", configuration = FeignClientsConfiguration.class)
public interface HelloApi {
    @GetMapping("/{name}")
    String hello(@PathVariable("name") String name);
}

Decoder feignDecoder

Decoder类,将http返回的Entity字符解码(反序列化)为我们需要的实例,如自定义的POJO对象。一般使用FeignClientsConfiguration默认的feignDecoder就能满足返回String、POJO等绝大多数场景。

@Bean
@ConditionalOnMissingBean
public Decoder feignDecoder() {
	return new OptionalDecoder(
		new ResponseEntityDecoder(new SpringDecoder(this.messageConverters)));
}

Encoder feignEncoder

Encode类对请求参数做编码(序列化)后,发送给http服务端。使用spring cloud默认的feignEncoder可以满足我们绝大多数情况。

使用Feign实现文件上传下载时需要特殊处理,使用feign-form能够方便的实现。这里我们对feign-form在spring cloud中的使用举一个简单的例子。

HelloApi接口声明:

public interface HelloApi {
    @GetMapping(value = "/download")
    byte[] download(HttpServletResponse response);

    @PostMapping(value = "upload", 
                 consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    ResponseValue<String> upload(@RequestBody MultipartFile file);
}

服务端代码:

@RestController
@RequestMapping("hello")
public class HelloController implements HelloApi {
    
    @Override
    public byte[] download(HttpServletResponse response) {
        FileInputStream fis = null;
        try{
            File file = new File("E:\\图片\\6f7cc39284868762caaed525.jpg");
            fis = new FileInputStream(file);
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition",
                               "attachment;filename=class.jpg");
            return IOUtils.toByteArray(fis, file.length());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
    
    @Override
    public ResponseValue<String> upload(@RequestBody MultipartFile file) {
        File destFile = new File("d:\\1.jpg");
        ResponseValue<String> response = new ResponseValue<>();
        try {
            file.transferTo(destFile);
            return response.ok("上传成功!", null);
        } catch (IOException e) {
            e.printStackTrace();
            return response.fail("上传失败,错误原因:"+e.getMessage());
        }
    }    
}

客户端代码:

pom.xml引入依赖:

<dependency>
    <groupId>io.github.openfeign.form</groupId>
    <artifactId>feign-form</artifactId>
    <version>3.8.0</version>
</dependency>
<dependency>
    <groupId>io.github.openfeign.form</groupId>
    <artifactId>feign-form-spring</artifactId>
    <version>3.8.0</version>
</dependency>

增加FeignClient配置类:

@Configuration
public class FeignMultipartSupportConfig extends FeignClientsConfiguration {
    @Bean
    public Encoder feignFormEncoder() {
        return new SpringFormEncoder();
    }
}

FeignClient接口声明:

import feign.Response;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;

@FeignClient(name="hello1", url = "127.0.0.1:8080", path = "hello",
        configuration = FeignMultipartSupportConfig.class)
public interface HelloApiExp extends HelloApi {
    @GetMapping("/download")
    Response download();
}

调用端代码:

@RestController
@RequestMapping("client")
public class HelloClient {

    @GetMapping(value = "/download")
    public byte[] download(HttpServletResponse response){
        response.setHeader("Content-Disposition",
                           "attachment;filename=class.jpg");
        //response.setHeader("Content-Type","application/octet-stream");

        Response resp = helloApi.download();
        Response.Body body = resp.body();
        try(InputStream is = body.asInputStream()) {
            return IOUtils.toByteArray(is, resp.body().length());
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
    
    @PostMapping(value = "upload", 
                 consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResponseValue<String> upload(@RequestBody MultipartFile file){
        return helloApi.upload(file);
    }    
}

Retryer feignRetryer

请求重试策略类,默认不重试,可配置成feign.Retryer.Default,启用重试,默认间隔100毫秒重试一次,最大间隔时间限制为1秒,最大重试次数5次。

@Configuration
public class FeignRetryConfig extends FeignClientsConfiguration {
    @Bean
    @Override
    public Retryer feignRetryer() {
        return new Retryer.Default();
    }
}

Feign.Builder feignBuilder

FeignClient的Builder,我们可以通过他使用代码的方式设置相关属性,代替@FeignClient的注解过的接口,如下面的代码:

@GetMapping("/hello/{name}")
public String hello(@PathVariable("name") String name){
    String response = feignBuilder
        .client(new OkHttpClient())
        .encoder(new SpringFormEncoder())
        .requestInterceptor(new ForwardedForInterceptor())
        .logger(new Slf4jLogger())
        .logLevel(Logger.Level.FULL)
        .target(String.class, "http://127.0.0.1:8080");

    return response;
    //return helloApi.hello(name);
}

其实@FeignClient生成的代理类也是通过它构建的。代码中的feignBuilder.client()可以使用RibbonClient,就集成了Ribben。

FeignLoggerFactory feignLoggerFactory

设置LoggerFactory类,默认为Slf4j。

Feign.Builder feignHystrixBuilder

配置Hystrix,从下面的配置类可以看出,@ConditionalOnClass({ HystrixCommand.class, HystrixFeign.class }) ,如果引用了Hystrix的相关依赖,并且属性feign.hystrix.enabled为true,则构建@FeignClient代理类时使用的FeignBuilder会使用feignHystrixBuilder。Feign通过这种方式集成了Hystrix。

@Configuration(proxyBeanMethods = false)
@ConditionalOnClass({ HystrixCommand.class, HystrixFeign.class })
protected static class HystrixFeignConfiguration {

   @Bean
   @Scope("prototype")
   @ConditionalOnMissingBean
   @ConditionalOnProperty(name = "feign.hystrix.enabled")
   public Feign.Builder feignHystrixBuilder() {
      return HystrixFeign.builder();
   }
}

OpenFeign+consul使用示例

背景介绍

本示例使用consul作为服务注册中心,基于SpringCloud框架开发两个微服务,一个user-service(服务提供方),一个feignusercommodity-service(服务调用方),具体版本信息如下

软件/框架 版本
consul v1.2.0
Spring Boot 2.0.1.RELEASE
Spring Cloud Finchley.RELEASE

openFeign使用默认版本的,也就是spring-cloud-starter-openfeign 2.0.0版本。

主要代码

核心代码主要包括两点,
1, 对应接口添加@FeignClient,并完成对应服务提供者的requestMapping映射。
2,在启动类加上@EnableFeignClients(basePackages = {"com.yq.client"}), 我的serviceClieng位于com.yq.client包。

提供方的主要接口如下:

userSvc001.png

ServiceClient类的主要实现如下.
注意:User 类在两个服务中是一样,实际项目中我们可以把它放到公共依赖包中。

@FeignClient(value = "user-service", fallbackFactory = UserServiceFallbackFactory.class)
public interface UserServiceClient {
    
    @RequestMapping(value="/v1/users/{userId}", method= RequestMethod.GET, produces = "application/json;charset=UTF-8")
    public User getUser(@PathVariable(value = "userId") String userId);

    @RequestMapping(value="/v1/users/queryById", method= RequestMethod.GET, produces = "application/json;charset=UTF-8")
    public User getUserByQueryParam(@RequestParam("userId") String userId);

    @RequestMapping(value="/v1/users", method= RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public String createUser();
}

完整代码看 user-servciefeignusercommodity-service,里面的pom文件,serviceClient都是完整的可以运行的。 欢迎加星,fork。

效果截图

第一张截图,两个服务都正常在consul上注册,完成服务间调用

consul001OK_FeignCall.png

第二张截图,两个服务都正常在consul上注册,完成服务间调用, 这是consul down了,服务间调用可以继续,因为feignusercommodity-service服务缓存了user-service服务的服务提供地址信息

consul002_shutdownConsul_CallOK.png

第三张截图,feignusercommodity-service服务正常在consul上注册,但是user-service没有注册,系统给出了“com.netflix.client.ClientException: Load balancer does not have available server for client: user-service”

consul003_userSvcOff.png

第四张截图,user-service提供方的对应方法报异常,服务调用能正常获取到该异常并显示。

consul004_svcCallOriginalSvcException.png

故障转移

使用Feign可以完成服务间调用,但是总存在一种情况:服务提供方没有注册到注册中心、服务提供方还没开发完成(因为也就无法调用)等等。此时如果我们需要完成服务间调用该如何做呢?

Feign提供了fallback机制,也就是当对方服务还没ready(一般情况是服务提供方在注册中心上没有可用的实例),可以返回信息供服务进行下,也就是服务降级

故障转移机制,如果@FeignClient指定了fallbackfallbackFactory属性,http请求调用失败时会路由到fallback处理类的相同方法中。

fallback

@FeignClient声明:

@FeignClient(name="hello1", url = "127.0.0.1:8080", path = "hello",
        configuration = FeignMultipartSupportConfig.class,
        fallback = HelloApiFallback.class)
public interface HelloApiExp extends HelloApi {
    @GetMapping("/download")
    Response download();
}

HelloApiFallback代码需要实现HelloApiExp接口(包括父接口)的所有方法:

@Slf4j
public class HelloApiFallback implements HelloApiExp {
    @Override
    public Response download() {
        log.error("下载文件出错。");
        return null;
    }

    @Override
    public String hello(String name) {
        log.error("调用hello接口出错。");
        return "调用hello接口出错,请联系管理员。";
    }

    @Override
    public ResponseValue<String> bye(String name) {
        log.error("调用bye接口出错。");
        ResponseValue<String> response = new ResponseValue<>();
        return response.fail("调用hello接口出错,请联系管理员。");
    }

    @Override
    public byte[] download(HttpServletResponse response) {
        log.error("调用bye接口出错。");
        return new byte[0];
    }

    @Override
    public ResponseValue<String> upload(MultipartFile file) {
        log.error("调用上传文件接口出错。");
        ResponseValue<String> response = new ResponseValue<>();
        return response.fail("上传文件出错,请联系管理员。");
    }
}

fallbackFactory

为@FeignClient接口所有方法指定统一的故障处理方法。

@FeignClient(name="hello1", url = "127.0.0.1:8080", path = "hello",
        configuration = FeignMultipartSupportConfig.class,
        fallbackFactory = FallbackFactory.Default.class)
public interface HelloApiExp extends HelloApi {

    @GetMapping("/download")
    Response download();
}

FallbackFactory.Default实现如下,请求失败后,统一路由到create(Throwable cause)方法。

/** Returns a constant fallback after logging the cause to FINE level. */
final class Default<T> implements FallbackFactory<T> {
  // jul to not add a dependency
  final Logger logger;
  final T constant;

  public Default(T constant) {
    this(constant, Logger.getLogger(Default.class.getName()));
  }

  Default(T constant, Logger logger) {
    this.constant = checkNotNull(constant, "fallback");
    this.logger = checkNotNull(logger, "logger");
  }

  @Override
  public T create(Throwable cause) {
    if (logger.isLoggable(Level.FINE)) {
      logger.log(Level.FINE, "fallback due to: " + cause.getMessage(), cause);
    }
    return constant;
  }

  @Override
  public String toString() {
    return constant.toString();
  }
}

Feign结合Hystrix可以实现服务降级

主要使用consul 1.2.0, Spring Boot 1.5.12, Spring Cloud Edgware.RELEASE。

需要引入Hystrix依赖并在启动类和配置文件中启用Hystrix

pom文件增加如下依赖

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

启动类加上@EnableHystrix@EnableHystrixDashboard@EnableFeignClients

@SpringBootApplication
@EnableHystrix
@EnableHystrixDashboard
@EnableDiscoveryClient
@EnableCircuitBreaker
//@EnableTurbine
@EnableFeignClients(basePackages = {"com.yq.client"})
public class HystrixDemoApplication {
    private static final Logger logger = LoggerFactory.getLogger(HystrixDemoApplication.class);

    public static void main(String[] args) {
        SpringApplication.run(HystrixDemoApplication.class, args);
        logger.info("HystrixDemoApplication Start done.");
    }
}

配置文件中feign启用hystrix

feign.hystrix.enabled=true

实现自己的fallback服务

feignClient类

@FeignClient(value = "user-service", fallback = UserServiceClientFallbackFactory.class)
@Component
public interface UserServiceClient {
    @RequestMapping(value = "/v1/users/{userId}", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    String getUserDetail(@PathVariable("userId") String userId);
}

自定义的fallback类

@Component
@Slf4j
public class UserServiceClientFallbackFactory implements UserServiceClient{
    @Override
    public String getUserDetail(String userId) {
        log.error("Fallback2, userId={}", userId);
        return "user-service not available2 when query '" + userId + "'";
    }
}

效果截图

第一张截图

虽然我们创建了fallback类,也引入了Hystrix,但是没有启用feign.hystrix.enabled=true,所以无法实现服务降级,服务间调用还是直接报异常。

feign001_NoEnableHystrix.png

第二张截图

我们创建了fallback类,也引入了Hystrix,同时启用feign.hystrix.enabled=true,所以当user-service不可用时,顺利实现服务降级。

feign002_EnableHystrix.png

第三张, user-service服务正常, fallback不影响原有服务间调用正常进行。

feign003_userServiceON.png

参考文档

官方文档在这里: http://cloud.spring.io/spring-cloud-openfeign/single/spring-cloud-openfeign.html

fallback官方文档:http://cloud.spring.io/spring-cloud-openfeign/single/spring-cloud-openfeign.html#spring-cloud-feign-hystrix-fallback

posted @ 2021-08-03 14:43  satire  阅读(1402)  评论(0编辑  收藏  举报