开发者

OpenFeign指定url方式调用的方式详解

目录
  • 引言
  • FeignClient注解配置URL
  • 实现RequestInterceptor接口?
  • 自定义FeignblockingLoadBalancerClient
  • BeanFactoryPostProcessor修改bean的url属性

引言

OpenFeign一般是结合注册中心一起使用的,也就是可以通过提供服务的名称而不是url来完成对目标服务的访问。但是出于本地调试的需要,或者考虑到一些简单的服务可能并不需要依赖注册中心,所以本篇我们就讲解一下OpenFeign直接通过目标服务的url进行调用的方式。

FeignClient注解配置URL

在@FeignClient注解的url属性中写一个固定的调用地址:

package com.morris.user.client;

import com.morris.user.entity.Order;
import org.springframework.cloud.openfeign.Feihttp://www.devze.comgnClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import Java.util.List;

/**
 * 指定url属性
 */
@FeignClient(value = "order-service", url = "http://localhost:8020", path = "/order", contextId = "orderUrl")
public interface OrderUrlClient {

    @GetMapping("findOrderByUserId")
    List<Order> findOrderByUserId(@RequestParam("userId") Long userId);

}

或者写一个可配置的地址,这样可以在配置文件里指定,可以根据不同的环境配置不同的URL,这种方式在创建feign客户端的时候就需要规划好:

@FeignClient(value = "order-service", url = "${customer.url}", path = "/order", contextId = "orderUrl")
public interface OrderUrlClient {

    @GetMapping("findOrderByUserId")
    List<Order> findOrderByUserId(@RequestParam("userId") Long userId);

}

实现RequestInterceptor接口?

实现RequestInterceptor接口在发起HTTP请求之前将注册中心调用方式修改为url方式调用。

在@FeignClient注解中指定configuration属性,这里并没有指定url属性:

package com.morris.user.client;

import com.morris.user.config.FeignUrlConfig;
import com.morris.user.entity.Order;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@FeignClient(value = "order-service", path = "/order", contextId = "orderUrl2", configuration = FeignUrlConfig.class)
public interface OrderUrlClient2 {

    @GetMapping("findOrderByUserId")
    List<Order> findOrderByUserId(@RequestParam("userId") Long userId);

}

FeignUrlConfig类中注入了一个RequestInterceptor类来拦截OrderUrlClient2中的请求,这里只会拦截OrderUrlClient2类中的请求:

package com.morris.user.config;

import feign.Logger;
import feign.Request;
import org.springframework.context.annotation.Bean;

public class FeignUrlConfig {

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

    @Bean
    public FeignUrlRequestInterceptor feignTraceRequestInterceptor() {
        return new FeignUrlRequestInterceptor();
    }
}

FeignUrlRequestInterceptor类中将请求的地址修改为具体的url,而不是之前的serviceId。

package com.morris.user.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;

public class FeignUrlRequestInterceptor implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate template) {
        System.out.println("old: " + template.url()); // /findOrderByUserId?userId=1
        template.target("http://localhost:8020/order");
        System.out.println("new: " + template.url()); // http://localhost:8020/order/findOrderByUserId?userId=1
    }
}

发起请求后抛出如下异XmnrqIzQ常:

java.lang.RuntimeException: Load balancer does not contain an instance for the service localhost
	at com.morris.user.config.FeignErrorDecoder.decode(FeignErrorDecoder.java:24) ~[classes/:na]

可以发现Feign还是会去注册中心寻找服务,这是为什么呢?

通过阅读FeignClientFactoryBean源码发现:

<T> T getTarget() {
  FeignContext context = applicationContext.getBean(FeignContext.class);
  Feign.Builder builder = feign(context);

  if (!StringUtils.hasText(url)) {
    if (!name.startsWith("http")) {
      url = "http://" + name;
    }
    else {
      url = name;
    }
    url += cleanPath();
    // url不存在
    return (T) loadBalance(builder, context,
        new HardCodedTarget<>(type, name, url));
  }
  if (StringUtils.hasText(url) && !url.startsWith("http")) {
    url = "http://" + url;
  }
  String url = this.url + cleanPath();
  Client client = getOptional(context, Client.class);
  if (client != null) {
    if (client instanceof LoadBalancerFeignClient) {
      // not load balancing because we have a url,
      // but ribbon is on the classpath, so unwrap
      client = ((LoadBalancerFeignClient) client).getDelegate();
    }
    if (client instanceof FeignBlockingLoadBalancerClient) {
      // not load balancing because we have a url,
      // but Spring Cloud LoadBalancer is on the classpath, so unwrap
      // url不存在
      client = ((FeignBlockingLoadBalancerClient) client).getDelegate();
    }
    builder.client(client);
  }
  Targeter targeter = get(context, Targeter.class);
  return (T) targeter.target(this, builder, context,
      new HardCodedTarget<>(type, name, url));
}

当@FeignClient中的url属性不存在时,底层的Client使用的是FeignBlockingLoadBalancerClient,这个Client会根据serviceId去注册中心查询服务,并进行负载均衡,虽然FeignUrlRequestInterceptor修改了url地址,但是Client会根据修改后的serviceId,也就是FeignUrlRequestInterceptor只能修改serviceId,不能改变调用方式。

当@FeignClient中的url属性存在时,底层的Client使用的是FeignBlockingLoadBalancerClient.getDelegate(),也就是ApacheHttpClient,这个client就不会去注册中心查询服务了,直接发起接口的调用。

自定义FeignBlockingLoadBalancerClient

自定义一个FeignBlockingLoadBalancerClient来改写url:

@FeignClient注解中指定configuration属性:

package com.morris.user.client;

import com.morris.user.config.OrderUrlClient3Config;
import com.morris.user.entity.Order;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@FeignClient(value = "order-service", path = "/order", contextId = "orderUrl3", configuration = OrderUrlClient3Config.class)
public interface OrderUrlClient3 {

    @GetMapping("findOrderByUserId")
    List<Order> findOrderByUserId(@RequestParam("userId") Long userId);

}

OrderUrlClient3Config类中注入了一个OrderUrlClient3Client类来拦截OrderUrlClient3中的请求,这里只会拦截OrderUrlClient3类中的请求,如果要实现全局的拦截,可以在OrderUrlClient3Config类上加@Configuration注解:

package com.morris.user.config;

import feign.Client;
import feign.Logger;
import org.springframework.context.annotation.Bean;

public class OrderUrlClient3Config {

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

    @Bean
    public OrderUrlClient3Client orderUrlClient3Client() {
        return new OrderUrlClient3Client(new Client.Default(null, null), null);
    }
}

OrderUrlClient3Client类继承了FeignBlockingLoadBalancerClient,重写了execute()方法:

package com.morris.user.config;

import feign.Client;
import feign.Request;
import feign.Response;
import org.springframework.cloud.loadbalancer.blocking.client.BlockingLoadBalancerClient;
import org.springframework.cloud.openfeign.loadbalancer.FeignBlockingLoadBalancerClient;
import org.springframework.web.util.UriComponentsBuilder;

import java.io.IOException;
import java.net.URI;

public class OrderUrlClient3Client extends FeignBlockingLoadBalancerClient {

    private final Client delegate;

    public OrderUrlClient3Client(Client delegate, BlockingLoadBalancerClient loadBalancerClient) {
        super(delegate, loadBalancerClient);
        this.delegate = delegate;
    }

    @Override
    public Response execute(Request request, Request.Options options) throws IOException {
        final URI originalUri = URI.create(request.url());
        // 修改url
        URI newUri = UriComponentsBuilder.fromUri(originalUri).host("localhost").port(8020)
                .build().toUri();
        Request newRequest = Request.create(request.httpMethod(), newUri.toString(),
                request.headers(), request.body(), request.charset(),
                request.requestTemplate());
        return delegate.execute(newRequest, options);
    }
}

BeanFactoryPostProcessor修改bean的url属性

这里可以使用Spring的扩展,给@FeignClient对应的Bean对象FeignClientFactoryBean加上url属性,这样在容器启动过程中就加上了url属性,feign创建的client为ApacheHttpClient,而不是FeignBlockingLoadBalancerClient

package com.morris.user.config;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.PropertyValue;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.fact编程客栈ory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.stereotype.Component;

import java.util.Objects;

@Component
public class OrderUrl4BeanFactoryPostProcessor implements BeanFactoryPostProcessor {
    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        if(!(beanFactory instanceof DefaultListableBeanFactory)) {
            return;
        }

        DefaultListableBeanFactory defaultListableBeanFactory = (DefaultListableBeanFactory) beanFactory;

        String[] bdNames = defaultListableBeanFactory.getBeanDefinitionNames();
       javascript for (String bdName : bdNames) {
            BeanDefinition beanDefinition = defaultListableBeanFactory.getBeanDefinition(bdName);

            if (!Objects.equals("org.springframework.cloud.openfeign.FeignClientFactoryBean", beanDefinition.getBeanClassName())) {
                continue;
            }

            if(!bdName.eqjavascriptuals("com.morris.user.client.OrderUrlClient4")) {
                // 这里只拦截OrderUrlClient4,放开就是全局
                continue;
            }

            PropertyValue urlPv = beanDefinition.getPropertyValues().getPropertyValue("url");
            if (Objects.nonNull(urlPv)) {
                Object value = urlPv.getValue();
                if (value instanceof String) {
                    String url = (String) value;
                    if (StringUtils.isNotBlank(url)) {
                        // 已指定url跳过
                        continue;
                    }
                }
            }

            // 相当于给@FeignClinet注解加上url属性
            beanDefinition.getPropertyValues().addPropertyValue("url", "http://localhost:8020");
        }
    }
}

到此这篇关于OpenFeign指定url方式调用的方式详解的文章就介绍到这了,更多相关OpenFeign指定url调用内容请搜索编程客栈(www.devze.com)以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程客栈(www.devze.com)!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新开发

开发排行榜