|
| 1 | +package feign.ribbon; |
| 2 | + |
| 3 | +import com.google.common.base.Throwables; |
| 4 | +import com.netflix.client.ClientException; |
| 5 | +import com.netflix.client.ClientFactory; |
| 6 | +import com.netflix.client.config.IClientConfig; |
| 7 | +import com.netflix.loadbalancer.ILoadBalancer; |
| 8 | + |
| 9 | +import java.io.IOException; |
| 10 | +import java.net.URI; |
| 11 | + |
| 12 | +import javax.net.ssl.HostnameVerifier; |
| 13 | +import javax.net.ssl.HttpsURLConnection; |
| 14 | +import javax.net.ssl.SSLSocketFactory; |
| 15 | + |
| 16 | +import feign.Client; |
| 17 | +import feign.Request; |
| 18 | +import feign.Response; |
| 19 | +import dagger.Lazy; |
| 20 | + |
| 21 | +/** |
| 22 | + * RibbonClient can be used in Fiegn builder to activate smart routing and resiliency capabilities provided by Ribbon. |
| 23 | + * Ex. |
| 24 | + * <pre> |
| 25 | + * MyService api = Feign.builder.client(new RibbonClient()).target(MyService.class, "http://myAppProd"); |
| 26 | + * </pre> |
| 27 | + * Where {@code myAppProd} is the ribbon client name and {@code myAppProd.ribbon.listOfServers} configuration |
| 28 | + * is set. |
| 29 | + */ |
| 30 | +public class RibbonClient implements Client { |
| 31 | + |
| 32 | + private final Client delegate; |
| 33 | + |
| 34 | + public RibbonClient() { |
| 35 | + this.delegate = new Client.Default( |
| 36 | + new Lazy<SSLSocketFactory>() { |
| 37 | + public SSLSocketFactory get() { |
| 38 | + return (SSLSocketFactory)SSLSocketFactory.getDefault(); |
| 39 | + } |
| 40 | + }, |
| 41 | + new Lazy<HostnameVerifier>() { |
| 42 | + public HostnameVerifier get() { |
| 43 | + return HttpsURLConnection.getDefaultHostnameVerifier(); |
| 44 | + } |
| 45 | + } |
| 46 | + ); |
| 47 | + } |
| 48 | + |
| 49 | + public RibbonClient(Client delegate) { |
| 50 | + this.delegate = delegate; |
| 51 | + } |
| 52 | + |
| 53 | + @Override public Response execute(Request request, Request.Options options) throws IOException { |
| 54 | + try { |
| 55 | + URI asUri = URI.create(request.url()); |
| 56 | + String clientName = asUri.getHost(); |
| 57 | + URI uriWithoutSchemeAndPort = URI.create(request.url().replace(asUri.getScheme() + "://" + asUri.getHost(), "")); |
| 58 | + LBClient.RibbonRequest ribbonRequest = new LBClient.RibbonRequest(request, uriWithoutSchemeAndPort); |
| 59 | + return lbClient(clientName).executeWithLoadBalancer(ribbonRequest).toResponse(); |
| 60 | + } catch (ClientException e) { |
| 61 | + if (e.getCause() instanceof IOException) { |
| 62 | + throw IOException.class.cast(e.getCause()); |
| 63 | + } |
| 64 | + throw Throwables.propagate(e); |
| 65 | + } |
| 66 | + } |
| 67 | + |
| 68 | + private LBClient lbClient(String clientName) { |
| 69 | + IClientConfig config = ClientFactory.getNamedConfig(clientName); |
| 70 | + ILoadBalancer lb = ClientFactory.getNamedLoadBalancer(clientName); |
| 71 | + return new LBClient(delegate, lb, config); |
| 72 | + } |
| 73 | +} |
0 commit comments