如何修改FeginCilent定义的服务名到指定服务

修改FeginCilent定义的服务名到指定服务

通过覆盖类来修改对应的服务名,这里将所有的FeginClient对应的服务名都修改好。

package org.springframework.cloud.openfeign;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionReaderUtils;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.env.Environment;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.ClassMetadata;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.core.type.filter.AbstractClassTestingTypeFilter;
import org.springframework.core.type.filter.AnnotationTypeFilter;
import org.springframework.core.type.filter.TypeFilter;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.util.StringUtils;
/**
 * @author Spencer Gibb
 * @author Jakub Narloch
 * @author Venil Noronha
 * @author Gang Li
 */
class FeignClientsRegistrar implements ImportBeanDefinitionRegistrar,
        ResourceLoaderAware, EnvironmentAware {
    private static Logger logger = LoggerFactory.getLogger(FeignClientsRegistrar.class);
    // patterned after Spring Integration IntegrationComponentScanRegistrar
    // and RibbonClientsConfigurationRegistgrar
    private ResourceLoader resourceLoader;
    private Environment environment;
    private String applicationName;
    public FeignClientsRegistrar() {
    }
    @Override
    public void setResourceLoader(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }
    @Override
    public void registerBeanDefinitions(AnnotationMetadata metadata,
                                        BeanDefinitionRegistry registry) {
        applicationName = environment.getProperty("cover.applicationName");
        if(applicationName == null){
            throw new NullPointerException("cover.baseline.applicationName 未配置 请配置后再启动");
        }
        logger.info("cover.baseline.applicationName 已配置 value = {}",applicationName);
        registerDefaultConfiguration(metadata, registry);
        registerFeignClients(metadata, registry);
    }
    private void registerDefaultConfiguration(AnnotationMetadata metadata,
                                              BeanDefinitionRegistry registry) {
        Map<String, Object> defaultAttrs = metadata
                .getAnnotationAttributes(EnableFeignClients.class.getName(), true);
        if (defaultAttrs != null && defaultAttrs.containsKey("defaultConfiguration")) {
            String name;
            if (metadata.hasEnclosingClass()) {
                name = "default." + metadata.getEnclosingClassName();
            } else {
                name = "default." + metadata.getClassName();
            }
            registerClientConfiguration(registry, name,
                    defaultAttrs.get("defaultConfiguration"));
        }
    }
    public void registerFeignClients(AnnotationMetadata metadata,
                                     BeanDefinitionRegistry registry) {
        ClassPathScanningCandidateComponentProvider scanner = getScanner();
        scanner.setResourceLoader(this.resourceLoader);
        Set<String> basePackages;
        Map<String, Object> attrs = metadata
                .getAnnotationAttributes(EnableFeignClients.class.getName());
        AnnotationTypeFilter annotationTypeFilter = new AnnotationTypeFilter(
                FeignClient.class);
        final Class<?>[] clients = attrs == null ? null
                : (Class<?>[]) attrs.get("clients");
        if (clients == null || clients.length == 0) {
            scanner.addIncludeFilter(annotationTypeFilter);
            basePackages = getBasePackages(metadata);
        } else {
            final Set<String> clientClasses = new HashSet<>();
            basePackages = new HashSet<>();
            for (Class<?> clazz : clients) {
                basePackages.add(ClassUtils.getPackageName(clazz));
                clientClasses.add(clazz.getCanonicalName());
            }
            AbstractClassTestingTypeFilter filter = new AbstractClassTestingTypeFilter() {
                @Override
                protected boolean match(ClassMetadata metadata) {
                    String cleaned = metadata.getClassName().replaceAll("\\$", ".");
                    return clientClasses.contains(cleaned);
                }
            };
            scanner.addIncludeFilter(
                    new AllTypeFilter(Arrays.asList(filter, annotationTypeFilter)));
        }
        for (String basePackage : basePackages) {
            Set<BeanDefinition> candidateComponents = scanner
                    .findCandidateComponents(basePackage);
            for (BeanDefinition candidateComponent : candidateComponents) {
                if (candidateComponent instanceof AnnotatedBeanDefinition) {
                    // verify annotated class is an interface
                    AnnotatedBeanDefinition beanDefinition = (AnnotatedBeanDefinition) candidateComponent;
                    AnnotationMetadata annotationMetadata = beanDefinition.getMetadata();
                    Assert.isTrue(annotationMetadata.isInterface(),
                            "@FeignClient can only be specified on an interface");
                    Map<String, Object> attributes = annotationMetadata
                            .getAnnotationAttributes(
                                    FeignClient.class.getCanonicalName());
                    String name = getClientName(attributes);
                    registerClientConfiguration(registry, name,
                            attributes.get("configuration"));
                    registerFeignClient(registry, annotationMetadata, attributes);
                }
            }
        }
    }
    private void registerFeignClient(BeanDefinitionRegistry registry,
                                     AnnotationMetadata annotationMetadata, Map<String, Object> attributes) {
        String className = annotationMetadata.getClassName();
        BeanDefinitionBuilder definition = BeanDefinitionBuilder
                .genericBeanDefinition(FeignClientFactoryBean.class);
        validate(attributes);
        definition.addPropertyValue("url", getUrl(attributes));
        definition.addPropertyValue("path", getPath(attributes));
        String name = getName(attributes);
        definition.addPropertyValue("name", name);
        definition.addPropertyValue("type", className);
        definition.addPropertyValue("decode404", attributes.get("decode404"));
        definition.addPropertyValue("fallback", attributes.get("fallback"));
        definition.addPropertyValue("fallbackFactory", attributes.get("fallbackFactory"));
        definition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE);
        String alias = name + "FeignClient";
        AbstractBeanDefinition beanDefinition = definition.getBeanDefinition();
        boolean primary = (Boolean) attributes.get("primary"); // has a default, won't be null
        beanDefinition.setPrimary(primary);
        String qualifier = getQualifier(attributes);
        if (StringUtils.hasText(qualifier)) {
            alias = qualifier;
        }
        BeanDefinitionHolder holder = new BeanDefinitionHolder(beanDefinition, className,
                new String[]{alias});
        BeanDefinitionReaderUtils.registerBeanDefinition(holder, registry);
    }
    private void validate(Map<String, Object> attributes) {
        AnnotationAttributes annotation = AnnotationAttributes.fromMap(attributes);
        // This blows up if an aliased property is overspecified
        // FIXME annotation.getAliasedString("name", FeignClient.class, null);
        Assert.isTrue(
                !annotation.getClass("fallback").isInterface(),
                "Fallback class must implement the interface annotated by @FeignClient"
        );
        Assert.isTrue(
                !annotation.getClass("fallbackFactory").isInterface(),
                "Fallback factory must produce instances of fallback classes that implement the interface annotated by @FeignClient"
        );
    }
    /* for testing */ String getName(Map<String, Object> attributes) {
        /*String name = (String) attributes.get("serviceId");
        if (!StringUtils.hasText(name)) {
            name = (String) attributes.get("name");
        }
        if (!StringUtils.hasText(name)) {
            name = (String) attributes.get("value");
        }
        name = resolve(name);
        if (!StringUtils.hasText(name)) {
            return "";
        }*/
        String name = applicationName;
        String host = null;
        try {
            String url;
            if (!name.startsWith("http://") && !name.startsWith("https://")) {
                url = "http://" + name;
            } else {
                url = name;
            }
            host = new URI(url).getHost();
        } catch (URISyntaxException e) {
        }
        Assert.state(host != null, "Service id not legal hostname (" + name + ")");
        return name;
    }
    private String resolve(String value) {
        if (StringUtils.hasText(value)) {
            return this.environment.resolvePlaceholders(value);
        }
        return value;
    }
    private String getUrl(Map<String, Object> attributes) {
        String url = resolve((String) attributes.get("url"));
        if (StringUtils.hasText(url) && !(url.startsWith("#{") && url.contains("}"))) {
            if (!url.contains("://")) {
                url = "http://" + url;
            }
            try {
                new URL(url);
            } catch (MalformedURLException e) {
                throw new IllegalArgumentException(url + " is malformed", e);
            }
        }
        return url;
    }
    private String getPath(Map<String, Object> attributes) {
        String path = resolve((String) attributes.get("path"));
        if (StringUtils.hasText(path)) {
            path = path.trim();
            if (!path.startsWith("/")) {
                path = "/" + path;
            }
            if (path.endsWith("/")) {
                path = path.substring(0, path.length() - 1);
            }
        }
        return path;
    }
    protected ClassPathScanningCandidateComponentProvider getScanner() {
        return new ClassPathScanningCandidateComponentProvider(false, this.environment) {
            @Override
            protected boolean isCandidateComponent(AnnotatedBeanDefinition beanDefinition) {
                boolean isCandidate = false;
                if (beanDefinition.getMetadata().isIndependent()) {
                    if (!beanDefinition.getMetadata().isAnnotation()) {
                        isCandidate = true;
                    }
                }
                return isCandidate;
            }
        };
    }
    protected Set<String> getBasePackages(AnnotationMetadata importingClassMetadata) {
        Map<String, Object> attributes = importingClassMetadata
                .getAnnotationAttributes(EnableFeignClients.class.getCanonicalName());
        Set<String> basePackages = new HashSet<>();
        for (String pkg : (String[]) attributes.get("value")) {
            if (StringUtils.hasText(pkg)) {
                basePackages.add(pkg);
            }
        }
        for (String pkg : (String[]) attributes.get("basePackages")) {
            if (StringUtils.hasText(pkg)) {
                basePackages.add(pkg);
            }
        }
        for (Class<?> clazz : (Class[]) attributes.get("basePackageClasses")) {
            basePackages.add(ClassUtils.getPackageName(clazz));
        }
        if (basePackages.isEmpty()) {
            basePackages.add(
                    ClassUtils.getPackageName(importingClassMetadata.getClassName()));
        }
        return basePackages;
    }
    private String getQualifier(Map<String, Object> client) {
        if (client == null) {
            return null;
        }
        String qualifier = (String) client.get("qualifier");
        if (StringUtils.hasText(qualifier)) {
            return qualifier;
        }
        return null;
    }
    private String getClientName(Map<String, Object> client) {
        if (client == null) {
            return null;
        }
        return applicationName;
      /* String value = (String) client.get("value");
        if (!StringUtils.hasText(value)) {
            value = (String) client.get("name");
        }
        if (!StringUtils.hasText(value)) {
            value = (String) client.get("serviceId");
        }
        if (StringUtils.hasText(value)) {
            return value;
        }
        throw new IllegalStateException("Either 'name' or 'value' must be provided in @"
                + FeignClient.class.getSimpleName());*/
    }
    private void registerClientConfiguration(BeanDefinitionRegistry registry, Object name,
                                             Object configuration) {
        BeanDefinitionBuilder builder = BeanDefinitionBuilder
                .genericBeanDefinition(FeignClientSpecification.class);
        builder.addConstructorArgValue(name);
        builder.addConstructorArgValue(configuration);
        registry.registerBeanDefinition(
                name + "." + FeignClientSpecification.class.getSimpleName(),
                builder.getBeanDefinition());
    }
    @Override
    public void setEnvironment(Environment environment) {
        this.environment = environment;
    }
    /**
     * Helper class to create a {@link TypeFilter} that matches if all the delegates
     * match.
     *
     * @author Oliver Gierke
     */
    private static class AllTypeFilter implements TypeFilter {
        private final List<TypeFilter> delegates;
        /**
         * Creates a new {@link AllTypeFilter} to match if all the given delegates match.
         *
         * @param delegates must not be {@literal null}.
         */
        public AllTypeFilter(List<TypeFilter> delegates) {
            Assert.notNull(delegates, "This argument is required, it must not be null");
            this.delegates = delegates;
        }
        @Override
        public boolean match(MetadataReader metadataReader,
                             MetadataReaderFactory metadataReaderFactory) throws IOException {
            for (TypeFilter filter : this.delegates) {
                if (!filter.match(metadataReader, metadataReaderFactory)) {
                    return false;
                }
            }
            return true;
        }
    }
}

FeginCilent动态服务名调用

工作碰到这个问题,解决后记录一下,废话不多说,直接上代码

@Data
@Configuration
@Import(FeignClientsConfiguration.class)
public class Test {
    private TestService testClient;

    //Feign 原生构造器
    Feign.Builder builder;

    //创建构造器
    public Test(Decoder decoder, Encoder encoder, Client client, Contract contract) {
        this.builder = Feign.builder()
                            .client(client)
                            .encoder(encoder)
                               .decoder(decoder)
                            .contract(contract);
    } 

	public void buildFeign(String url) {
        this.testClient = builder.target(TestService.class, url);
    }
}
	@RequestMapping(value = "test",method = RequestMethod.GET)
    @ResponseBody
    public void test(){
    	String url = "http://cyn-admin";
    	service.buildFeign(url);
    	System.out.println(service.getTestClient().dictList());
    }

以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。

(0)

相关推荐

  • Spring cloud踩坑记录之使用feignclient远程调用服务404的方法

    前言 公司项目进行微服务改造,由之前的dubbo改用SpringCloud,微服务之间通过FeignClient进行调用,今天在测试的时候,eureka注册中心有相应的服务,但feignclient就是无法调通,一直报404错误,排查过程如下: 一.问题: 服务提供方定义的接口如下: /** * 黑白名单查询接口 * * @author LiJunJun * @since 2018/10/18 */ @Component(value = "blackAndWhiteListFeignClient

  • 详解springcloud 基于feign的服务接口的统一hystrix降级处理

    springcloud开发微服务时,基于feign来做声明式服务接口,当启用hystrix服务熔断降级时,项目服务众多,每个Feign服务接口都得写一些重复问的服务降级处理代码,势必显得枯燥无味: Feign服务接口: @FeignClient(name="springcloud-nacos-producer", qualifier="productApiService", contextId="productApiService", fallb

  • 详解spring cloud feign踩坑记录

    1:多客户端时,feign接口抽取到公共jar中,此时,客户端的启动类上需要对该jar中feign所在的包进行扫描,要在spring和feign中同时注册,否则启动时会报:"Consider defining a bean of type '******Feign' in your configuration." @SpringBootApplication @EnableTransactionManagement @EnableDiscoveryClient @ComponentSc

  • Spring Cloud中关于Feign的常见问题总结

    一.FeignClient接口,不能使用@GettingMapping 之类的组合注解 代码示例: @FeignClient("microservice-provider-user") public interface UserFeignClient { @RequestMapping(value = "/simple/{id}", method = RequestMethod.GET) public User findById(@PathVariable(&quo

  • 解决feignClient调用时获取返回对象类型匹配的问题

    feignClient调用时获取返回对象类型匹配 feignClient是springCloud体系中重要的一个组件,用于微服务之间的相互调用,底层为httpClient,在之前的应用中,我一直以为A服务提供的方法返回类型为对象的话,那么调用A服务的B服务必须也用字段类型以及命名完全相同的对象来接收,为此我验证了一下,发现不是必须用完全相同的对象来接收,比如,可以用map<String,Object>或者Object来接收,然后解析. 当然,复杂对象我还是推荐用一个完全相同的对象来接收. 下面

  • 如何修改FeginCilent定义的服务名到指定服务

    修改FeginCilent定义的服务名到指定服务 通过覆盖类来修改对应的服务名,这里将所有的FeginClient对应的服务名都修改好. package org.springframework.cloud.openfeign; import java.io.IOException; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.

  • mysql8.0忘记密码修改与net命令服务名无效问题

    cmd中输入net start mysql 提示:服务名无效 请进入MySQL的bin目录,并在bin目录打开命令行窗口,或设置系统环境变量,在命令行窗口输入:mysqld --install,回车,提示:Service successfully installed. 表示安装MySQL服务成功,命令行窗口输入:net start mysql ,可以正常启动 mysql8.0忘记密码修改: 亲测下面这个代码是可行的 明明在前面安装MySQL的时候有要你设置一个密码,但是其实那个密码貌似用不到,这

  • JDK反序列化时修改类的全限定性名解析

    应用场景 SpringSecurityOAuth2有一个奇葩的设计,那就是它将与access_token相关的所有属于都封装到OAuth2AccessToken中,然后保存时会直接将该对象序列化成字节写入数据库.我们在资源服务器中想要直接读数据库来取出access_token来验证令牌的有效性,然而又不想引入SpringSecurity的相关依赖污染jar包.这时可以将SpringSecurity中OAuth2AccessToken的唯一实现类DefaultOAuth2AccessToken的源

  • mysql运行net start mysql报服务名无效的解决办法

    运行net start mysql报服务名无效的解决办法,供大家参考,具体内容如下 1. 症状 以前电脑上安装了 MySQL,今天在电脑上运行,发现没有 MySQL 服务了 C:UsersAdministrator>net start mysql 服务名无效. 请键入 NET HELPMSG 2185 以获得更多的帮助 2. 解决办法 输入 mysqld.exe -install MySQL 安装在:D:\wamp\bin\mysql\mysql5.1.53 以上就是本文的全部内容,希望对大家的

  • ubuntu修改terminal终端的主机名的实现方法

    ubuntu修改terminal终端的主机名的实现方法 有时候安装完Ubuntu系统后,打开命令终端,终端显示的主机名格式比较难看,例如 我最近买的国内某云的VPS. xxx@VM-1560-ubuntu$ xxx@VM-1560-ubuntu$ 对于有洁癖的人来说,看到这么长还带横杆的系统名就烦,想进各种方法消除他,还好,linux上命令修改特别方便. 一.关于hostname命令 hostname命令在linux上可以查看以及设置当前系统的名字 1. 查看hostname xxx@VM-15

  • T-sql语句修改SQL Server数据库逻辑名、数据库名、物理名的方法

    本文实例讲述了T-sql语句修改SQL Server数据库逻辑名.数据库名.物理名的方法.分享给大家供大家参考,具体如下: 更改MSSQL数据库物理文件名Sql语句的写法 注意:要在活动监视器里面确保没有进程连接你要改名的数据库!!!!!!!!!!!!!!!!!!!! Sql语句如下 USE master --改逻辑名 ALTER DATABASE YQBlog MODIFY FILE(NAME='YQBlogAA',NEWNAME='YQBlog') -- GO ALTER DATABASE

  • Linux修改网卡名称、主机名的方法

    Linux修改网卡名称.主机名 环境:VirtualBox 5.0.14 + RHEL 6.5 需求:个人实验搭建一套Standby RAC时,为了节约时间,直接复制之前安装RAC的主机模板. 但复制之后发现网卡名称不一致: 我这里的环境,Primary RAC的Public IP和Private IP分别对应的网卡名称是eth2,eth3.  而复制Standby RAC的其中一台网卡名称是eth6,eth7:另一台是eth4,eth5.为了保持一致方便后续管理维护,需要将Standby RA

  • 解决net start MongoDB 报错之服务名无效的问题

    解决 1. 先检查自己的配置信息,如若一切无误后,则使用管理员模式开启cmd,不要直接打开cmd. 2. 然后在cmd中转跳至自己MongoDB的bin目录,使用我的举例是: cd "C:\Program Files\MongoDB\Server\3.4\bin" 3. 然后cmd写入服务 mongod --dbpath "D:\MongodbData\data" --logpath "D:\MongodbData\logs\mongodb.log&quo

  • spring cloud gateway使用 uri: lb://方式配置时,服务名的特殊要求

    在gateway中配置uri配置有三种方式,包括 第一种:ws(websocket)方式: uri: ws://localhost:9000 第二种:http方式: uri: http://localhost:8130/ 第三种:lb(注册中心中服务名字)方式: uri: lb://brilliance-consumer 其中ws和http方式不容易出错,因为http格式比较固定,但是lb方式比较灵活自由.不考虑网关,只考虑服务时,服务名命名时比较自由,都能启动被访问,被注册到注册中心,但是如果

  • mysql 5.7安装 MySQL 服务无法启动但是服务没有报告任何错误

    MySQL 5.7的安装有两种方式,一种是下载安装程序,点击安装,另一种是下载压缩包,直接解压,配置一下就可以运行了 个人更喜欢压缩包的形式,所以本文记录的也是压死包形式的安装(配置) https://dev.mysql.com/downloads/mysql/ 我下载的最新的是 mysql-5.7.17-win32.zip 加压到mysql-5.7.17-win32文件夹,后文提到的文件和文件夹都以此为更目录 把bin目录配置到环境变量path的后面 我的是  ;D:\mysql-5.7.17

随机推荐