Home > Java > Java Tutorial > body text

spring cloud2.0 study notes Feign practice

无忌哥哥
Release: 2018-07-20 12:02:45
Original
3227 people have browsed it

Background

  • springCloud:Finchley.RELEASE

Introduction

Feign is a declarative Rest client in the Spring Cloud system. It can call Restful services through simple configuration, creation of interfaces and annotations. And it starts to support SpringMvc.

Simple application

  • Dependency: org.springframework.cloud:spring-cloud-starter-openfeign

  • Entry plus @ EnableFeignClients annotation

  • Create the corresponding interface and add annotation

//入口类
@SpringBootApplication
@EnableFeignClientspublic class Application {

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

}
//原型接口声明
@FeignClient("stores")public interface StoreClient {
    @RequestMapping(method = RequestMethod.GET, value = "/stores")
    List getStores();    
    @RequestMapping(method = RequestMethod.POST, value = "/stores/{storeId}", consumes = "application/json")
    Store update(@PathVariable("storeId") Long storeId, Store store);
}
Copy after login

Enable Feign circuit breaker and context support

  • feign.hystrix.enabled=true

# To disable Hystrix in Feignfeign:
  hystrix:
    enabled: true# To set thread isolation to SEMAPHORE# 将断路器隔离级别由默认的线程隔离调整为信号灯hystrix:
  command:    default:
      execution:
        isolation:
          strategy: SEMAPHORE
Copy after login

Circuit breaker callback

The circuit breaker supports fallback, which means that the callback definition is executed when the circuit breaker is turned on or an error occurs on the interface. Method that returns predefined results. To enable callback support, you only need to configure the fallback parameter in the @FeignClient annotation to be the callback implementation class of the interface, and the callback implementation class must be annotated as a Spring Bean (can be implemented through @Component, @Service and other annotations, see the annotation documentation of Spring 4 for details).

@FeignClient(name = "hello", fallback = HystrixClientFallback.class)
protected interface HystrixClient {
    @RequestMapping(method = RequestMethod.GET, value = "/hello")
    Hello iFailSometimes();
}

@Componentstatic class HystrixClientFallback implements HystrixClient {
    @Override    
    public Hello iFailSometimes() {        
        return new Hello("fallback");
    }
}
Copy after login

If you need to know the reason for the rollback, you can use the rollback factory. The code example is as follows:

@FeignClient(name = "hello", fallbackFactory = HystrixClientFallbackFactory.class)
protected interface HystrixClient {
    @RequestMapping(method = RequestMethod.GET, value = "/hello")
    Hello iFailSometimes();
}

@Componentstatic class HystrixClientFallbackFactory implements FallbackFactory {
    @Override    public HystrixClient create(Throwable cause) {        
        return new HystrixClient() {
            @Override            
            public Hello iFailSometimes() {                
                return new Hello("fallback; reason was: " + cause.getMessage());
            }
        };
    }
}
Copy after login

Feign supports interface inheritance

Feign supports interface inheritance. Operations form contracts through interfaces.

//生产者的控制层接口public interface UserService {

    @RequestMapping(method = RequestMethod.GET, value ="/users/{id}")
    User getUser(@PathVariable("id") long id);
}
//生产者的控制器实现
@RestController
public class UserResource implements UserService {}
//消费端的Feign接口定义
package project.user;
@FeignClient("users")
public interface UserClient extends UserService {}
Copy after login

Compression support

Enabling compression can effectively save network resources, but it will increase CPU pressure. It is recommended to increase the minimum compressed document size appropriately

//开启压缩
feign.compression.request.enabled=true
feign.compression.response.enabled=true

//配置压缩文档类型及最小压缩的文档大小
feign.compression.request.mime-types=text/xml,application/xml,application/json
feign.compression.request.min-request-size=2048
Copy after login

Log configuration

  • The package where the interface of the consumer service is located must be debug

# 日志支持logging.level.project.user.UserClient: DEBUG
Copy after login
  • Define a custom configuration class and define the log level

@Configurationpublic class FooConfiguration {
    @Bean
    Logger.Level feignLoggerLevel() {        
        return Logger.Level.FULL;
    }
}
Copy after login
  • Log level

    • ##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.

The above is the detailed content of spring cloud2.0 study notes Feign practice. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!