spring-cloud-openFeign详解

GitHub地址
官方文档地址

1、引入OpenFeign依赖

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

2、定义FeignClict 接口

使用@FeignClient(name = 服务名,path = 服务下controller类上路径,configuration = feign配置)

package com.mj.feign.serive.nacos;

import com.mj.feign.config.FeignConfig;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;

@FeignClient(name = "api-nacos", path = "/nacos", configuration = FeignConfig.class)
public interface NacosFeignService {

    @GetMapping("/get")
    String getUsername();
}

3、配置启动类

添加@EnableFeignClients 可以指定包名@EnableFeignClients({“com.mj.feign.*”})

@SpringBootApplication
@EnableFeignClients
public class JayNacosApplication {
    public static void main(String[] args) {
        SpringApplication.run(JayNacosApplication.class, args);
    }
}

4、Feign配置类

package com.mj.feign.config;

import com.mj.feign.intercept.CustomizeIntercept;
import feign.Logger;
import feign.Request;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * OpenFeign 配置类  还可以通过 配置文件配置
 * 全局配置: 当使用@Configuration 会将配置作用所有的服务提供方
 * 局部配置:1、 通过配置类  如果只针对某一个服务进行配置,就不要加@Configuration   在对应的Feign 接口加上 configuration = FeignConfig.class
 * 局部配置:2、 通过配置文件 feign: client: config: 服务名: loggerLevel: BASIC
 */
@Configuration
public class FeignConfig {

    /**
     * Feign 请求日志配置  2、配置文件方式 feign: client: config: 服务名: loggerLevel: BASIC
     *
     * @return
     */
    @Bean
    public Logger.Level feignLoggerLevel() {
        return Logger.Level.FULL;
    }

    /**
     * 超时时间配置   2、配置文件方式 feign: client: config: 服务名: readTimeout: 10000 connectTimeout: 5000
     * @return
     */
    @Bean
    public Request.Options options(){
        // 连接超时时间   读取超时时间
        return new Request.Options(5000,10000);
    }

    /**
     * 自定义拦截器配置  2、配置文件方式 feign: client: config: 服务名:requestInterceptor[0]: com.mj.feign.intercept.CustomizeIntercept
     */

    @Bean
    public CustomizeIntercept customizeIntercept(){
        return new CustomizeIntercept();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值