springcloud feign本地微服务之间的相互调用

一、随着项目微服务数量越来越多,本地调试的时候很容易把请求打到别人的机器上或者云上环境,所以用自定义注解的方式实现微服务本地之间调用,使用起来也非常简单,只需要在启动类上加一个注解即可。

1.编写自定义注解

java 复制代码
import org.springframework.context.annotation.Import;

import java.lang.annotation.*;

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
@Documented
@Import(FeignClientsServiceNameAppendBeanPostProcessor.class)
public @interface EnableLocalHostFeign {
    String[] serverNameAndUrl() default {};

}

2:加一个规则配置类,在bean交给spring管理之前更改url

java 复制代码
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Field;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Pattern;

@Slf4j
public class FeignClientsServiceNameAppendBeanPostProcessor implements BeanPostProcessor, ApplicationContextAware {

    private ApplicationContext applicationContext;


    private AtomicInteger atomicInteger = new AtomicInteger();
    private static final Pattern pattern = Pattern
            .compile("^([hH][tT]{2}[pP]://|[hH][tT]{2}[pP][sS]://)(([A-Za-z0-9-~]+).)+([A-Za-z0-9-~\\/])+$");

    @SneakyThrows
    @Override
    @Async
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (atomicInteger.getAndIncrement() == 0) {
            String[] serverNameAndUrl = null;
            String[] beanNamesForAnnotation = applicationContext.getBeanNamesForAnnotation(EnableLocalHostFeign.class);
            for (String s : beanNamesForAnnotation) {
                if (s.contains(".")) {
                    continue;
                }
                Class<?> aClass1 = applicationContext.getBean(s).getClass();
                EnableLocalHostFeign annotation1 = AnnotationUtils.findAnnotation(aClass1, EnableLocalHostFeign.class);
                serverNameAndUrl = annotation1.serverNameAndUrl();
            }
            if (serverNameAndUrl == null || serverNameAndUrl.length == 0) {
                log.info("Annotation not found EnableLocalHostFeign");
                return null;
            }
            String beanNameOfFeignClientFactoryBean = "org.springframework.cloud.openfeign.FeignClientFactoryBean";
            Class beanNameClz = Class.forName(beanNameOfFeignClientFactoryBean);
            String[] finalserverNameAndUrl = serverNameAndUrl;
            applicationContext.getBeansOfType(beanNameClz).forEach((feignBeanName, beanOfFeignClientFactoryBean) -> {
                try {
                    for (String server : finalserverNameAndUrl) {
                        if (!server.contains("=")) {
                            log.info("EnableLocalHostFeign serverNameAndUrl error,skip");
                            continue;
                        }
                        int i = server.indexOf("=");
                        String finalServerName = server.substring(0, i).replaceAll("\\s*", "");
                        String finalServerUrl = server.substring(i + 1, server.length()).replaceAll("\\s*", "");

                        if (!pattern.matcher(finalServerUrl).matches()) {
                            log.info("EnableLocalHostFeign url error,skip");
                            continue;
                        }
                        String serverName = getFiled(beanNameClz, "name", beanOfFeignClientFactoryBean);
                        if (serverName.equals(finalServerName)) {
                            setField(beanNameClz, "url", beanOfFeignClientFactoryBean, finalServerUrl);
                            log.info("EnableLocalHostFeign : " + feignBeanName + "-->" + beanOfFeignClientFactoryBean);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
        }
        return null;
    }

    private String getFiled(Class clazz, String fieldName, Object obj) throws Exception {
        Field field = ReflectionUtils.findField(clazz, fieldName);
        if (Objects.nonNull(field)) {
            ReflectionUtils.makeAccessible(field);
            Object value = field.get(obj);
            if (Objects.nonNull(value)) {
                return value.toString();
            }
        }
        return null;
    }

    private void setField(Class clazz, String fieldName, Object obj, String url) throws Exception {
        Field field = ReflectionUtils.findField(clazz, fieldName);
        if (Objects.nonNull(field)) {
            ReflectionUtils.makeAccessible(field);
            ReflectionUtils.setField(field, obj, url);
        }
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    public static void main(String[] args) {
        String url1 = "http://www.xx.com";
        String url2 = "w.xx.com";
        String url3 = "http://w.xx.com";
        String url4 = "ssss";
        String url5 = "http://localhost:9012";
        Pattern pattern = Pattern
                .compile("^([hH][tT]{2}[pP]://|[hH][tT]{2}[pP][sS]://)(([A-Za-z0-9-~]+).)+([A-Za-z0-9-~\\/])+$");
        System.out.println(pattern.matcher(url1).matches());
        System.out.println(pattern.matcher(url2).matches());
        System.out.println(pattern.matcher(url3).matches());
        System.out.println(pattern.matcher(url4).matches());
        System.out.println(pattern.matcher(url5).matches());

    }
}

3.使用方法:springboot项目启动类添加@EnableLocalHostFeign注解,参数传值规则:项目名=项目地址。

java 复制代码
@EnableDiscoveryClient
@EnableFeignClients(basePackages = {"xxx"})
@SpringBootApplication(scanBasePackages = {"xxx"},
        exclude= {DataSourceAutoConfiguration.class})
@EnableLocalHostFeign(serverNameAndUrl ={ "项目名=项目地址",
        "hello-world-server = http://localhost:9006","hello-world-server2=http://192.168.1.8:9001"})
public class xxxxxApplication {
    public static void main(String[] args) {
        SpringApplication.run(xxxxxApplication.class, args);
    }

}

4.效果:控制台会打印如下日志:后面显示的替换的本地微服务

相关推荐
雨中飘荡的记忆1 小时前
Spring AI + MCP:从入门到实战
java·人工智能·spring
市安1 小时前
去dockerHub搜索并拉取一个redis镜像
redis·spring cloud·docker·eureka
CodeToGym1 小时前
【Spring全家桶】Spring Cache 深度解析:一行注解实现缓存自动化
spring·缓存·自动化
七夜zippoe1 小时前
客户端负载均衡器深度解析 Spring Cloud LoadBalancer与Ribbon源码剖析
spring cloud·ribbon·负载均衡·loadbalancer·核心机制
崎岖Qiu1 小时前
SpringBoot:基于注解 @PostConstruct 和 ApplicationRunner 进行初始化的区别
java·spring boot·后端·spring·javaee
人道领域1 小时前
javaWeb从入门到进阶(SpringBoot基础案例)
java·开发语言·spring
草履虫建模2 小时前
A02 Maven 基础配置:本地仓库、镜像、项目编码与常见问题(IDEA 实战)
xml·java·spring boot·spring·maven·intellij-idea·idea
indexsunny2 小时前
互联网大厂Java面试实战:Spring Boot微服务在电商场景中的应用
java·数据库·spring boot·redis·微服务·kafka·电商
sww_10262 小时前
Spring-AI MCP 源码浅析
java·人工智能·spring
没有bug.的程序员2 小时前
Spring Boot 性能优化:启动时间从 5s 到 1s 的全链路实战指南
java·spring boot·后端·spring·性能优化·全链路·启动时间