一些收藏

Spring Cloud-Feign Http客户端

2022-03-07  本文已影响0人  石头耳东

前置文章:
一、Spring Cloud-Erueka服务注册&发现
二、Spring Cloud-Nacos服务注册&发现
三、Spring Cloud-Nacos配置管理

零、本文纲要

tips:Ctrl + F快速定位到所需内容阅读吧。

一、RestTemplate Http客户端

由于我们的服务调用都是基于Http协议进行的,所以代码中不得不使用Http相应的客户端来进行服务间沟通。RestTemplate是Spring Web提供的Http客户端,org.springframework.web.client.RestTemplate。

    @Autowired
    private RestTemplate restTemplate;
    ...
        String url = "http://userservice/user/" + order.getUserId();
        User user = restTemplate.getForObject(url, User.class);
    ...

使用RestTemplate带来的问题:①代码可读性差;②参数url难维护。

二、Feign Http客户端快速入门

Spring Cloud OpenFeign 官方入口

        <!--开启对Feign的支持-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>
        <!--配置Feign一起使用-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-loadbalancer</artifactId>
        </dependency>

Spring Boot启动类上添加@EnableFeignClients注解。

@MapperScan("com.stone.mapper")
@SpringBootApplication
@EnableFeignClients
public class SpringCloudOrderserviceApplication {
    ...
}

①编写客户端接口UserClient
②添加@FeignClient(value = "userservice")注解
③编写接口方法@GetMapping("/user/{id}")
④请求参数Long id
⑤返回值User

@FeignClient(value = "userservice")
public interface UserClient {
    @GetMapping("/user/{id}")
    public User findById(@PathVariable("id") Long id);
}
    @Override
    public Order queryOrderById(Long id){
        //1.查询订单
        Order order = orderMapper.findById(id);
        //2.使用Fegin远程调用
        User user = userClient.findById(order.getUserId());
        //3.封装User至Order
        order.setUser(user);
        //4.返回结果
        return order;
    }

至此,我们的Feign快速入门的代码就编写完成了。

注意:由于Feign使用的LoadBalancer与Nacos默认使用的Robbin不一致,此时可能会报错。需要在Nacos的依赖项内做对应排除,以解决依赖冲突引发的问题。具体如下:

        <!-- nacos客户端依赖包 -->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
            <!--避免与Feign负载均衡策略冲突-->
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.cloud</groupId>
                    <artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

三、自定义Feign配置

Feign Logging 官方文档入口

feign:
  client:
    config:
      default: # 这里用default就是全局配置,如果是写服务名称,则是针对某个微服务的配置
      #userservice:
        loggerLevel: BASIC #NONE\BASIC\HEADERS\FULL

①配置类:

public class LoggerFeignConfiguration {
    @Bean
    public Logger.Level feignLogLevel(){
        return Logger.Level.NONE;
    }
}

②@EnableFeignClients注解配置生效

@MapperScan("com.stone.mapper")
@SpringBootApplication
@EnableFeignClients(defaultConfiguration = LoggerFeignConfiguration.class)
public class SpringCloudOrderserviceApplication {
    ...
}

③@FeignClient注解配置生效

@FeignClient(value = "userservice", configuration = LoggerFeignConfiguration.class)
public interface UserClient {
    @GetMapping("/user/{id}")
    public User findById(@PathVariable("id") Long id);
}

注意:application.yml配置优先级优于注解配置。

默认为NONE等级,LOG等级越高信息越详细,但是性能反而下降。建议维持NONE等级,或者仅调整为BASIC等级。
①NONE, No logging (DEFAULT).
②BASIC, Log only the request method and URL and the response status code and execution time.(打印连接和断开信息)
③HEADERS, Log the basic information along with request and response headers.
④FULL, Log the headers, body, and metadata for both requests and responses.

四、Feign性能优化

使用HttpClient实例:
Ⅰ 相关依赖

        <!--HttpClient的依赖 -->
        <dependency>
            <groupId>io.github.openfeign</groupId>
            <artifactId>feign-httpclient</artifactId>
        </dependency>

Ⅱ 配置连接池

feign:
  client:
    config:
      default: # 这里用default就是全局配置,如果是写服务名称,则是针对某个微服务的配置
      #userservice:
        loggerLevel: BASIC #NONE\BASIC\HEADERS\FULL
  httpclient:
    enabled: true # 开启对HttpClient的支持
    max-connections: 200 # 最大连接数
    max-connections-per-route: 50 # 每个路径的最大连接数

其余内容无需调整,即可使用。

虽然Feign比起RestTemplate看起来确实更优雅,但是比起Dubbo的服务调用还是有些逊色。

五、结尾

以上即为Feign基础使用的内容,感谢阅读。

上一篇 下一篇

猜你喜欢

热点阅读