springcloud之feign

springcloud之feign

a declarative REST client for Spring Boot apps

Dependency

spring-cloud-starter-openfeign

Code

  • @EnableFeignClients
  • declare a Feign client using the @FeignClient annotation
@SpringBootApplication
@EnableFeignClients
public class ExampleApplication {

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

@FeignClient(value = "jplaceholder", url = "https://jsonplaceholder.typicode.com/")
public interface JSONPlaceHolderClient {

@RequestMapping(method = RequestMethod.GET, value = "/posts")
List<Post> getPosts();

@RequestMapping(method = RequestMethod.GET, value = "/posts/{postId}", produces = "application/json")
Post getPostById(@PathVariable("postId") Long postId);
}

Configuration

FeignClientsConfiguration

  • Decoder – ResponseEntityDecoder, which wraps SpringDecoder, used to decode the Response
  • Encoder – SpringEncoder, used to encode the RequestBody
  • Logger – Slf4jLogger is the default logger used by Feign
  • Feign-Builder – HystrixFeign.Builder used to construct the components
  • Client – LoadBalancerFeignClient or default Feign client
@FeignClient(value = "jplaceholder",
url = "https://jsonplaceholder.typicode.com/",
configuration = MyClientConfiguration.class)

Eg customeize client - okClient

@Configuration
public class MyClientConfiguration {

@Bean
public OkHttpClient client() {
return new OkHttpClient();
}
}

also support config using properties


feign:
client:
config:
default:
connectTimeout: 5000
readTimeout: 5000
loggerLevel: basic

Interceptor

The interceptors can perform a variety of implicit tasks, from authentication to logging, for every HTTP request/response.

Eg

@Bean
public RequestInterceptor requestInterceptor() {
return requestTemplate -> {
requestTemplate.header("user", username);
requestTemplate.header("password", password);
requestTemplate.header("Accept", ContentType.APPLICATION_JSON.getMimeType());
};
}

feign:
client:
config:
default:
requestInterceptors:
{intercetpr calss}

hystrix support

Fallback.

  • feign.hystrix.enabled=true

eg

@Component
public class JSONPlaceHolderFallback implements JSONPlaceHolderClient {

@Override
public List<Post> getPosts() {
return Collections.emptyList();
}

@Override
public Post getPostById(Long postId) {
return null;
}
}

@FeignClient(value = "jplaceholder",
url = "https://jsonplaceholder.typicode.com/",
fallback = JSONPlaceHolderFallback.class)
public interface JSONPlaceHolderClient {
// APIs
}

https://www.baeldung.com/spring-cloud-openfeign