美文网首页
Spring-Cloud系列 Feign (三)

Spring-Cloud系列 Feign (三)

作者: KKKnight_ | 来源:发表于2018-05-29 09:33 被阅读95次

    什么是Feign?

        Feign是一个声明式Web服务客户端。支持可插拔编码器和解码器。Spring Cloud的Feign添加了对Spring MVC注释的支持,并且使用了Spring Web中默认使用的相同HttpMessageConverters。Spring Cloud的Feign将Ribbon和Eureka集成在一起,在使用Feign时提供负载均衡的http客户端。

    快速开始

    这个案例依赖Eureka-Server,请准备好server服务。Eureka相关查看Spring-Cloud系列(一) Eureka

    添加依赖

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.13.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <spring-cloud.version>Dalston.SR5</spring-cloud.version>
    </properties>
    
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka</artifactId>
        </dependency>
    
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-feign</artifactId>
        </dependency>
    
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
    
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
    
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
    

    代码

    注解扫描

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

    定义客户端

    @FeignClient("eureka-client-one") //必须是你调用服务的名称,即spring.application.name
    public interface FeignTestClient {
    
        /**
         * Feign默认解析合约是Spring-MVC的注解
         * @return
         */
        @RequestMapping(method = RequestMethod.GET, value = "/url")
        String getUrl();
    }
    

    使用

    @Autowired
    private FeignTestClient feignTestClient;
    
    @GetMapping("/test")
    public String testService(){
        return feignTestClient.getUrl();
    }
    

    application配置

    server:
    </br>  port: 8083
    </br>spring:
    </br>  application:
    </br>    name: feign-one
    </br>eureka:

    </br>  instance:
    </br>    prefer-ip-address: true
    </br>    instanceId: ${spring.application.name}:${vcap.application.instance_id:${spring.application.instance_id:${random.value}}}
    </br>  client:
    </br>    serviceUrl:
    </br>      defaultZone: http://user:Pass123456@localhost:8761/eureka

    启动效果

    [图片上传失败...(image-bfe5a9-1527557581139)]

    自定义feignClient和feign日志登等级

    配置定义客户端

    自定义配置

    @Configuration
    public class FeignConfiguration {
        
        @Bean
        public Contract feignContract() {
            return new feign.Contract.Default();
        }
    }
    

    定义客户端

    @FeignClient(name = "eureka-client-one",configuration = FeignConfiguration.class) 
    public interface FeignTestClient {
        @RequestLine("GET /url") //根据配置现在Feign支持的是原生注解
        String getUrl();
    }
    

      注意!Feign的客户端的自定义和Ribbon类似,配置类不能放在启动类的平级和子目录下。否则会覆盖全局配置,正确目录如下:</br>

    目录结构

    代码定义客户端

    定义客户端

    public interface FeignTestClient {
        @RequestLine("GET /url")
        String getUrl();
    }
    

    使用客户端

    @RestController
    @Import(FeignClientsConfiguration.class)
    public class FeignTestContoller {
    
        @GetMapping("/test")
        public String testService(){
            FeignTestClient feignTestClient = Feign.builder()
                    .options(new Request.Options(1000, 3500))
                    .retryer(new Retryer.Default(5000, 5000, 3))
                    .requestInterceptor(new BasicAuthRequestInterceptor("user", "Pass123456"))
                    .target(FeignTestClient.class, "http://lodalhost:8080");
            return feignTestClient.getUrl();
        }
    }
    

    Feign提供的配置

        Feign提供以下默认配置:

    • Decoder feignDecoder: ResponseEntityDecoder (which wraps a SpringDecoder)
    • Encoder feignEncoder: SpringEncoder
    • Logger feignLogger: Slf4jLogger
    • Contract feignContract: SpringMvcContract
    • Feign.Builder feignBuilder: HystrixFeign.Builder
    • Client feignClient: if Ribbon is enabled it is a LoadBalancerFeignClient, otherwise the default feign client is used.

        Feign未提供默认配置:

    • Logger.Level
    • Retryer
    • ErrorDecoder
    • Request.Options
    • Collection<RequestInterceptor>
    • SetterFactory

    自定义日志级别

    application配置

    logging:
    </br>  level:
    </br>    com.midai.feign.client.FeignTestClient: DEBUG #Client是用户自定义Clien全称

    代码配置

    @Configuration
    public class FeignConfiguration {
        @Bean
        Logger.Level feignLoggerLevel() {
            return Logger.Level.FULL;
        }
    }
    

    Feign的可选日志等级

    • 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其他用法和配置

    抽取公用包依赖

    UserService.java

    public interface UserService {
        @RequestMapping(method = RequestMethod.GET, value ="/users/{id}")
        User getUser(@PathVariable("id") long id);
    }
    

    UserResource.java

    @RestController
    public class UserResource implements UserService {
    }
    

    UserClient.java

    @FeignClient("users")
    public interface UserClient extends UserService {
    }
    

        接口抽取共用,服务提供方直接实现,FeignClient继承提高代码可用性。

    Feign请求响应设置

    Feign请求响应压缩

    feign:
    </br>  compression:
    </br>    request:
    </br>      enabled: true
    </br>feign:

    </br>  compression:
    </br>    response:
    </br>      enabled: true

    Feign请求设置

    feign:

    </br>  compression:
    </br>    request:
    </br>      mime-types: text/xml,application/xml,application/json
    </br>feign:
    </br>  compression:
    </br>    request:
    </br>      min-request-size: 2048

        本文参考Spring-Cloud-FeignFeign-Builder用法

    相关文章

      网友评论

          本文标题:Spring-Cloud系列 Feign (三)

          本文链接:https://www.haomeiwen.com/subject/fpjojftx.html