spring cloud openFeign

本文介绍了OpenFeign的基本概念及其在Java Http客户端中的作用,通过一个具体的示例展示了如何创建`order-service`和`user-service`项目,演示了如何在`user-service`中使用OpenFeign进行服务调用并实现负载均衡。同时,文章还提到了OpenFeign的熔断降级机制,展示了如何配置回退方法以处理服务请求失败的情况。

一、openFeign简介

openFeign是一种伪声明式RPC,它旨在使编写Java Http客户端变得更容易,它的性能主要体现在它的通信层面上。

参考资料一参考资料二

二、通过demo来学习

  首先,我们需要一个“order项目”,我们通过部署多个订单系统来分散订单压力;其次我们需要一个“user项目”,在“user项目”上我们需要实现客户端的负载均衡。

1、order-service订单项目

新建一个spring项目,项目名称为“order-service”。

(1)、项目依赖

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

(2)、application.properties配置文件

spring.application.name=order-service
server.port=8080

(3)、项目代码

package com.example;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class OrderController {

    @Value("${server.port}")
    private int port;

    @GetMapping("getOrder")
    public String getOrder(){
        return "获取订单信息,服务端口:"+port;
    }

}

订单项目构建好后,我们可以启动多个订单服务。IDEA启动多个服务

2、user-service用户系统

新建一个spring项目,项目名称为“user-service”。

(1)、项目依赖

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

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

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

(2)、application.properties配置文件

spring.application.name=user-service
server.port=8070

#配置指定服务提供者的列表
order-service.ribbon.listOfServers=\
  localhost:8080,localhost:8081

(3)、项目代码

新建FeignClient接口,添加@FeignClient注解,配置应用服务名“order-service”

package com.example;

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

@FeignClient("order-service")
public interface OrderServiceFeignClient {

    @GetMapping("getOrder")
    String getOrder();

}
package com.example;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class OpenFeignController {

    @Autowired
    private OrderServiceFeignClient orderServiceFeignClient;

    @GetMapping("feignClientMethod")
    public String feignClientMethod(){
        return orderServiceFeignClient.getOrder();
    }

}

另外我们需要在spring入口类中添加@EnableFeignClients注解来开启openFeign。如果我们的feignClient接口和入口类不在同级目录下,我们还需要配置basePackages,例如:

@EnableFeignClients(basePackages = "com.example.clients")
package com.example;

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

@SpringBootApplication
@EnableFeignClients
public class UserServiceApplication {

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

}

三、总结

    另外open-feign还提供了熔断降级机制,我们可以通过“fallback”配置来提供请求的默认返回参数,处理返回异常。详见以下代码。

@FeignClient(value = "order-service",fallback = OrderServiceFeignClientImpl.class)
public interface OrderServiceFeignClient {

    @GetMapping("getOrder")
    String getOrder();
}

 

import org.springframework.stereotype.Component;

@Component
public class OrderServiceFeignClientImpl implements OrderServiceFeignClient {

    @Override
    public String getOrder() {
//接口请求失败,默认返回此处的提示信息
        return "查询订单失败,请稍后重试!";
    }
}

 

### OpenFeign 使用指南与配置示例 Spring Cloud OpenFeign 是一个基于 Feign 的声明式服务调用客户端,它与 Spring Cloud 生态系统深度集成,提供了强大的服务发现、负载均衡和自定义请求处理能力。以下是 OpenFeign 的使用指南和配置示例。 #### 1. 启用 OpenFeign 客户端 要在 Spring Boot 应用中启用 OpenFeign 客户端,需要在主类上添加 `@EnableFeignClients` 注解。该注解会扫描所有使用 `@FeignClient` 注解的接口,并为它们创建代理对象。 ```java import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.openfeign.EnableFeignClients; @SpringBootApplication @EnableFeignClients public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` #### 2. 定义 Feign 客户端接口 通过 `@FeignClient` 注解定义远程服务的接口,指定服务称或 URL,并使用 Spring MVC 的注解来定义请求路径和参数。 ```java import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.GetMapping; @FeignClient(name = "hello-service") public interface HelloServiceClient { @GetMapping("/hello") String sayHello(); } ``` #### 3. 自定义配置 OpenFeign 支持针对特定服务的自定义配置。例如,可以为 `hello-service` 设置连接和读取超时时间、日志级别等。 ```yaml spring: cloud: openfeign: client: config: hello-service: connect-timeout: 3000 read-timeout: 30000 url: http://localhost:8081 logger-level: full ``` #### 4. 请求拦截器 OpenFeign 允许开发者通过实现 `RequestInterceptor` 接口,在请求发送前后添加自定义逻辑,例如添加请求头、日志记录等。 ```java import feign.RequestInterceptor; import feign.RequestTemplate; public class CustomRequestInterceptor implements RequestInterceptor { @Override public void apply(RequestTemplate template) { template.header("X-Custom-Header", "CustomValue"); } } ``` 在 Spring 配置中注册拦截器: ```java import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class FeignConfig { @Bean public RequestInterceptor customRequestInterceptor() { return new CustomRequestInterceptor(); } } ``` #### 5. 负载均衡与服务发现 OpenFeign 可以与 Spring Cloud服务发现组件(如 Eureka)集成,自动获取服务实例信息并进行负载均衡。确保在 `pom.xml` 或 `build.gradle` 中引入了 Eureka Client 和 OpenFeign 的依赖。 ```xml <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency> ``` #### 6. 性能优化 为了提升 OpenFeign 的性能,可以通过以下方式进行优化: - **连接池**:使用 Apache HttpClient 或 OkHttp 作为底层 HTTP 客户端,并配置连接池以提高性能。 - **超时设置**:合理配置连接和读取超时时间,避免因网络问题导致请求阻塞。 - **负载均衡**:利用 Ribbon 或 Spring Cloud LoadBalancer 实现更高效的负载均衡策略。 #### 7. 日志级别 OpenFeign 提供了多种日志级别,可以通过配置文件或编程方式设置。例如,设置为 `full` 级别可以记录完整的请求和响应信息。 ```yaml logging: level: com.example.client.HelloServiceClient: DEBUG ``` #### 8. 自定义解码器与编码器 如果需要处理特定格式的请求或响应数据,可以自定义 `Decoder` 和 `Encoder`。例如,使用 Fastjson 替代默认的 Jackson 解码器。 ```java import com.alibaba.fastjson.JSON; import feign.Response; import feign.codec.Decoder; import java.io.IOException; import java.lang.reflect.Type; public class FastJsonDecoder implements Decoder { @Override public Object decode(Response response, Type type) throws IOException { return JSON.parseObject(response.body().asInputStream(), type); } } ``` 在配置类中注册: ```java import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class FeignConfig { @Bean public Decoder feignDecoder() { return new FastJsonDecoder(); } } ``` #### 9. 异常处理 OpenFeign 支持自定义异常解码器,用于处理远程服务调用时可能抛出的异常。 ```java import feign.Response; import feign.codec.ErrorDecoder; public class CustomErrorDecoder implements ErrorDecoder { @Override public Exception decode(String methodKey, Response response) { return new RuntimeException("Feign client error occurred"); } } ``` 注册异常解码器: ```java import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class FeignConfig { @Bean public ErrorDecoder feignErrorDecoder() { return new CustomErrorDecoder(); } } ``` ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值