Search in sources :

Example 1 with Client

use of feign.Client in project nutzboot by nutzam.

the class FeignStarter method afterBorn.

@SuppressWarnings({ "unchecked", "rawtypes" })
public Object afterBorn(Object obj, String beanName) {
    try {
        Mirror mirror = Mirror.me(obj);
        for (Field field : obj.getClass().getDeclaredFields()) {
            FeignInject fc = field.getAnnotation(FeignInject.class);
            if (fc == null)
                continue;
            String url = Strings.sBlank(conf.get(PROP_URL), "http://127.0.0.1:8080");
            Encoder encoder = getEncoder(fc, field);
            Decoder decoder = getDecoder(fc, field);
            Client client = getClient(fc, field, url);
            Logger.Level level = Level.valueOf(conf.get(PROP_LOGLEVEL, "BASIC").toUpperCase());
            Class apiType = field.getType();
            Logger logger = new Slf4jLogger(apiType);
            boolean useHystrix = "true".equals(Strings.sBlank(fc.useHystrix(), conf.get(PROP_HYSTRIX_ENABLE)));
            Feign.Builder builder = useHystrix ? HystrixFeign.builder() : Feign.builder();
            if (encoder != null)
                builder.encoder(encoder);
            if (decoder != null)
                builder.decoder(decoder);
            if (client != null)
                builder.client(client);
            builder.logger(logger);
            builder.logLevel(level);
            int connectTimeout = fc.connectTimeout();
            if (connectTimeout == 0)
                connectTimeout = conf.getInt(PROP_CONNECT_TIMEOUT, 10 * 1000);
            int readTimeout = fc.readTimeout();
            if (readTimeout == 0)
                readTimeout = conf.getInt(PROP_READ_TIMEOUT, 10 * 1000);
            builder.options(new Options(connectTimeout, readTimeout));
            Object t = null;
            if (useHystrix) {
                t = ((HystrixFeign.Builder) builder).target(apiType, url, getFallbackIocBean(apiType, fc.fallback()));
            } else {
                t = builder.target(apiType, url);
            }
            mirror.setValue(obj, field.getName(), t);
        }
    } catch (Throwable e) {
        throw new RuntimeException(e);
    }
    return obj;
}
Also used : Options(feign.Request.Options) Slf4jLogger(feign.slf4j.Slf4jLogger) Decoder(feign.codec.Decoder) JAXBDecoder(feign.jaxb.JAXBDecoder) JacksonDecoder(feign.jackson.JacksonDecoder) GsonDecoder(feign.gson.GsonDecoder) Logger(feign.Logger) Slf4jLogger(feign.slf4j.Slf4jLogger) FeignInject(org.nutz.boot.starter.feign.annotation.FeignInject) Level(feign.Logger.Level) HystrixFeign(feign.hystrix.HystrixFeign) Field(java.lang.reflect.Field) Encoder(feign.codec.Encoder) JacksonEncoder(feign.jackson.JacksonEncoder) GsonEncoder(feign.gson.GsonEncoder) JAXBEncoder(feign.jaxb.JAXBEncoder) Feign(feign.Feign) HystrixFeign(feign.hystrix.HystrixFeign) RibbonClient(feign.ribbon.RibbonClient) EurekaClient(com.netflix.discovery.EurekaClient) Client(feign.Client) OkHttpClient(feign.okhttp.OkHttpClient) ApacheHttpClient(feign.httpclient.ApacheHttpClient) LBClient(feign.ribbon.LBClient) Mirror(org.nutz.lang.Mirror)

Example 2 with Client

use of feign.Client in project spring-cloud-sleuth by spring-cloud.

the class FeignRetriesTests method testRetriedWhenExceededNumberOfRetries.

@Test
public void testRetriedWhenExceededNumberOfRetries() throws Exception {
    Client client = (request, options) -> {
        throw new IOException();
    };
    String url = "http://localhost:" + server.getPort();
    TestInterface api = Feign.builder().client(new TracingFeignClient(this.httpTracing, client)).target(TestInterface.class, url);
    try {
        api.decodedPost();
        failBecauseExceptionWasNotThrown(FeignException.class);
    } catch (FeignException e) {
    }
}
Also used : Mock(org.mockito.Mock) RunWith(org.junit.runner.RunWith) Span(zipkin2.Span) HashMap(java.util.HashMap) Client(feign.Client) ErrorParser(org.springframework.cloud.sleuth.ErrorParser) CurrentTraceContext(brave.propagation.CurrentTraceContext) ExceptionMessageErrorParser(org.springframework.cloud.sleuth.ExceptionMessageErrorParser) Charset(java.nio.charset.Charset) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) After(org.junit.After) ArrayListSpanReporter(org.springframework.cloud.sleuth.util.ArrayListSpanReporter) MockWebServer(okhttp3.mockwebserver.MockWebServer) FeignException(feign.FeignException) Before(org.junit.Before) Tracing(brave.Tracing) HttpTracing(brave.http.HttpTracing) Response(feign.Response) SleuthHttpParserAccessor(org.springframework.cloud.sleuth.instrument.web.SleuthHttpParserAccessor) RequestLine(feign.RequestLine) IOException(java.io.IOException) Test(org.junit.Test) BDDAssertions.then(org.assertj.core.api.BDDAssertions.then) Feign(feign.Feign) BDDMockito(org.mockito.BDDMockito) Rule(org.junit.Rule) BeanFactory(org.springframework.beans.factory.BeanFactory) Request(feign.Request) MockitoJUnitRunner(org.mockito.junit.MockitoJUnitRunner) Assertions.failBecauseExceptionWasNotThrown(org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown) FeignException(feign.FeignException) IOException(java.io.IOException) Client(feign.Client) Test(org.junit.Test)

Example 3 with Client

use of feign.Client in project spring-cloud-sleuth by spring-cloud.

the class FeignRetriesTests method testRetriedWhenRequestEventuallyIsSent.

@Test
public void testRetriedWhenRequestEventuallyIsSent() throws Exception {
    String url = "http://localhost:" + server.getPort();
    final AtomicInteger atomicInteger = new AtomicInteger();
    // Client to simulate a retry scenario
    final Client client = (request, options) -> {
        // we simulate an exception only for the first request
        if (atomicInteger.get() == 1) {
            throw new IOException();
        } else {
            // with the second retry (first retry) we send back good result
            return Response.builder().status(200).reason("OK").headers(new HashMap<>()).body("OK", Charset.defaultCharset()).build();
        }
    };
    TestInterface api = Feign.builder().client(new TracingFeignClient(this.httpTracing, new Client() {

        @Override
        public Response execute(Request request, Request.Options options) throws IOException {
            atomicInteger.incrementAndGet();
            return client.execute(request, options);
        }
    })).target(TestInterface.class, url);
    then(api.decodedPost()).isEqualTo("OK");
    // request interception should take place only twice (1st request & 2nd retry)
    then(atomicInteger.get()).isEqualTo(2);
    then(this.reporter.getSpans().get(0).tags()).containsEntry("error", "IOException");
    then(this.reporter.getSpans().get(1).kind().ordinal()).isEqualTo(Span.Kind.CLIENT.ordinal());
}
Also used : Mock(org.mockito.Mock) RunWith(org.junit.runner.RunWith) Span(zipkin2.Span) HashMap(java.util.HashMap) Client(feign.Client) ErrorParser(org.springframework.cloud.sleuth.ErrorParser) CurrentTraceContext(brave.propagation.CurrentTraceContext) ExceptionMessageErrorParser(org.springframework.cloud.sleuth.ExceptionMessageErrorParser) Charset(java.nio.charset.Charset) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) After(org.junit.After) ArrayListSpanReporter(org.springframework.cloud.sleuth.util.ArrayListSpanReporter) MockWebServer(okhttp3.mockwebserver.MockWebServer) FeignException(feign.FeignException) Before(org.junit.Before) Tracing(brave.Tracing) HttpTracing(brave.http.HttpTracing) Response(feign.Response) SleuthHttpParserAccessor(org.springframework.cloud.sleuth.instrument.web.SleuthHttpParserAccessor) RequestLine(feign.RequestLine) IOException(java.io.IOException) Test(org.junit.Test) BDDAssertions.then(org.assertj.core.api.BDDAssertions.then) Feign(feign.Feign) BDDMockito(org.mockito.BDDMockito) Rule(org.junit.Rule) BeanFactory(org.springframework.beans.factory.BeanFactory) Request(feign.Request) MockitoJUnitRunner(org.mockito.junit.MockitoJUnitRunner) Assertions.failBecauseExceptionWasNotThrown(org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown) Response(feign.Response) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) HashMap(java.util.HashMap) Request(feign.Request) IOException(java.io.IOException) Client(feign.Client) Test(org.junit.Test)

Example 4 with Client

use of feign.Client in project atlasdb by palantir.

the class CounterBackedRefreshingClientTest method reinvokesSupplierAfterTheSpecifiedNumberOfRequestsHaveBeenMade.

@Test
public void reinvokesSupplierAfterTheSpecifiedNumberOfRequestsHaveBeenMade() throws IOException {
    when(clientSupplier.get()).thenReturn(client);
    when(client.execute(request, options)).thenReturn(Response.create(204, "no content", ImmutableMap.of(), new byte[0]));
    Client refreshingClient = new CounterBackedRefreshingClient(clientSupplier, 2);
    refreshingClient.execute(request, options);
    refreshingClient.execute(request, options);
    refreshingClient.execute(request, options);
    verify(clientSupplier, times(2)).get();
    verify(client, times(3)).execute(request, options);
    verifyNoMoreInteractions(clientSupplier, client);
}
Also used : Client(feign.Client) Test(org.junit.Test)

Example 5 with Client

use of feign.Client in project atlasdb by palantir.

the class CounterBackedRefreshingClientTest method requestsContinueWithOldClientIfDelegateSupplierThrows.

@Test
public void requestsContinueWithOldClientIfDelegateSupplierThrows() throws IOException {
    when(clientSupplier.get()).thenReturn(client);
    when(client.execute(request, options)).thenReturn(Response.create(204, "no content", ImmutableMap.of(), new byte[0]));
    Client refreshingClient = new CounterBackedRefreshingClient(clientSupplier, 2);
    refreshingClient.execute(request, options);
    when(clientSupplier.get()).thenThrow(new IllegalStateException("bad"));
    refreshingClient.execute(request, options);
    // Creation failed, so we delegate to the old client still.
    refreshingClient.execute(request, options);
    verify(clientSupplier, times(2)).get();
    verify(client, times(3)).execute(request, options);
    verifyNoMoreInteractions(clientSupplier, client);
}
Also used : Client(feign.Client) Test(org.junit.Test)

Aggregations

Client (feign.Client)12 Test (org.junit.Test)8 Request (feign.Request)5 Response (feign.Response)4 Feign (feign.Feign)3 RequestLine (feign.RequestLine)3 IOException (java.io.IOException)3 Charset (java.nio.charset.Charset)3 MockWebServer (okhttp3.mockwebserver.MockWebServer)3 Rule (org.junit.Rule)3 Tracing (brave.Tracing)2 HttpTracing (brave.http.HttpTracing)2 CurrentTraceContext (brave.propagation.CurrentTraceContext)2 FeignException (feign.FeignException)2 Logger (feign.Logger)2 Level (feign.Logger.Level)2 Options (feign.Request.Options)2 Decoder (feign.codec.Decoder)2 JacksonDecoder (feign.jackson.JacksonDecoder)2 JacksonEncoder (feign.jackson.JacksonEncoder)2