網(wǎng)站首頁(yè) 編程語(yǔ)言 正文
一、隨著項(xiàng)目微服務(wù)數(shù)量越來(lái)越多,本地調(diào)試的時(shí)候很容易把請(qǐng)求打到別人的機(jī)器上或者云上環(huán)境,所以用自定義注解的方式實(shí)現(xiàn)微服務(wù)本地之間調(diào)用,使用起來(lái)也非常簡(jiǎn)單,只需要在啟動(dòng)類上加一個(gè)注解即可。
1.編寫自定義注解
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:加一個(gè)規(guī)則配置類,在bean交給spring管理之前更改url
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項(xiàng)目啟動(dòng)類添加@EnableLocalHostFeign注解,參數(shù)傳值規(guī)則:項(xiàng)目名=項(xiàng)目地址。
@EnableDiscoveryClient
@EnableFeignClients(basePackages = {"xxx"})
@SpringBootApplication(scanBasePackages = {"xxx"},
exclude= {DataSourceAutoConfiguration.class})
@EnableLocalHostFeign(serverNameAndUrl ={ "項(xiàng)目名=項(xiàng)目地址",
"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.效果:控制臺(tái)會(huì)打印如下日志:后面顯示的替換的本地微服務(wù)
原文鏈接:https://blog.csdn.net/weixin_42714698/article/details/124764624
相關(guān)推薦
- 2022-11-06 MobLink?Android端業(yè)務(wù)場(chǎng)景簡(jiǎn)單說(shuō)明_Android
- 2022-04-25 C++的靜態(tài)類型檢查詳解_C 語(yǔ)言
- 2022-05-10 筆記本能連接 WiFi,但在瀏覽器中并不能訪問(wèn)網(wǎng)頁(yè)的問(wèn)題的四種方案;
- 2022-10-02 C#使用is、as關(guān)鍵字以及顯式強(qiáng)轉(zhuǎn)實(shí)現(xiàn)引用類型轉(zhuǎn)換_C#教程
- 2023-01-13 Pytorch中關(guān)于BatchNorm2d的參數(shù)解釋_python
- 2022-06-13 Docker執(zhí)行DockerFile構(gòu)建過(guò)程指令解析_docker
- 2022-04-11 canvas實(shí)現(xiàn)畫板功能
- 2022-10-05 WPF實(shí)現(xiàn)好看的Loading動(dòng)畫的示例代碼_C#教程
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細(xì)win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運(yùn)行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲(chǔ)小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運(yùn)算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認(rèn)證信息的處理
- Spring Security之認(rèn)證過(guò)濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯(cuò)誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實(shí)現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡(jiǎn)單動(dòng)態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對(duì)象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊(duì)列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠(yuǎn)程分支