纯净、安全、绿色的下载网站

首页|软件分类|下载排行|最新软件|IT学院

当前位置:首页IT学院IT技术

nacos动态路由配置 关于springboot中nacos动态路由的配置

Spring王不正   2021-09-11 我要评论
想了解关于springboot中nacos动态路由的配置的相关内容吗,Spring王不正在本文为您仔细讲解nacos动态路由配置的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:springboot配置,nacos动态路由,nacos配置,下面大家一起来学习吧。

nacos动态路由的配置

什么都不说了,springboot-nacos 不懂得的下面自行学习啦我直接贴下代码!

首先。。。

我自己有个服务器。在无聊之时写的代码,主要是通过网关来调用接口所以有了下面的代码。

1.作为一个动态路由维护管理的类

@Service
public class DynamicRouteServiceImpl  implements ApplicationEventPublisherAware {
    /**
     *
     */
    @Autowired
    private RouteDefinitionWriter routeDefinitionWriter;
    private ApplicationEventPublisher publisher;
    /**
     * 增加路由
     * @param definition
     * @return
     */
    public String add(RouteDefinition definition) {
        routeDefinitionWriter.save(Mono.just(definition)).subscribe();
        this.publisher.publishEvent(new RefreshRoutesEvent(this));
        return "success";
    }
    /**
     * 更新路由
     * @param definition
     * @return
     */
    public String update(RouteDefinition definition) {
        try {
            this.routeDefinitionWriter.delete(Mono.just(definition.getId()));
        } catch (Exception e) {
            return "update fail,not find route  routeId: "+definition.getId();
        }
        try {
            routeDefinitionWriter.save(Mono.just(definition)).subscribe();
            this.publisher.publishEvent(new RefreshRoutesEvent(this));
            return "success";
        } catch (Exception e) {
            return "update route  fail";
        }
    }
    /**
     * 删除路由
     * @param id
     * @return
     */
    public String delete(String id) {
        try {
            this.routeDefinitionWriter.delete(Mono.just(id));
            return "delete success";
        } catch (Exception e) {
            e.printStackTrace();
            return "delete fail";
        }
    }
    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
        this.publisher = applicationEventPublisher;
    }

2.基于Nacos动态配置路由服务

@Component
public class DynamicRouteServiceImplByNacos implements CommandLineRunner {
    private static final Logger logger = LoggerFactory.getLogger(DynamicRouteServiceImplByNacos.class);
    @Autowired
    private DynamicRouteServiceImpl dynamicRouteService;
    @Value("${spring.cloud.nacos.discovery.server-addr}")
    private String address;
    @Value("${config.dataId}")
    private String dataId;
    @Value("${config.groupId}")
    private String groupId;
    @Value("${config.timeout}")
    private Long timeout;
   /* @Value("${config.ignore}")
    private String ignore;*/
    /**
     * 监听Nacos Server下发的动态路由配置
     */
    public void dynamicRouteByNacosListener() {
        try {
            ConfigService configService = NacosFactory.createConfigService(address);
            configService.addListener(dataId, groupId, new Listener() {
                @Override
                public void receiveConfigInfo(String configInfo) {
                    try {
                        logger.info("================Nacos 配置中心路由配置信息已修改================\n" + configInfo + "\n\n");
                        List<RouteDefinition> list = JSON.parseArray(configInfo, RouteDefinition.class);
                        list.forEach(definition -> {
                            dynamicRouteService.update(definition);
                        });
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                @Override
                public Executor getExecutor() {
                    return null;
                }
            });
            /*configService.addListener(ignore, groupId, new Listener() {
                @Override
                public void receiveConfigInfo(String configInfo) {
                    try {
                        logger.info("================Nacos 配置中心忽略URL配置已修改================\n" + configInfo + "\n\n");
                        logger.info("\n" + configInfo + "\n\n");
                        List<String> ignoreList = JSON.parseArray(configInfo, String.class);
                        IgnoreRouteConfig.setIgnoreRouteArr(ignoreList);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                @Override
                public Executor getExecutor() {
                    return null;
                }
            });*/
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    @Override
    public void run(String... args) throws Exception {
        dynamicRouteByNacosListener();
    }
}

3.yml配置

在这里插入图片描述

4. nacos网关配置

在这里插入图片描述

5.最后:我建的是

父子工程两个服务发到服务器后 注意注意注意!!!:一定要开启防火墙,登上阿里云自己的服务增加端口,然后再linux中也要增加端口 linux防火墙相关命令

  • 删除 firewall-cmd --zone= public --remove-port=80/tcp --permanent
  • 开放 firewall-cmd --zone=public --add-port=1935/tcp --permanent
  • 查看状态 systemctl status firewalld
  • 启动 systemctl start firewalld
  • 查看已开启端口 firewall-cmd --list-ports
  • 重启 firewall-cmd --reload

在这里插入图片描述

yml配置文件中 有一个这个端口 这个也要在阿里云上面还有服务器开启

这个就是接口访问时的网关端口号

在这里插入图片描述

Springboot配置Nacos出现的问题

报错信息

java.lang.ClassNotFoundException:org.springframework.boot.context.properties.ConfigurationBeanFactoryMetadata

由于当前Nacos版本还不支持Springboot 2.4.+ 的版本,所以需要降一个版本 为2.3.+

具体如下

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'configurationPropertiesBeans' defined in class path resource [org/springframework/cloud/autoconfigure/ConfigurationPropertiesRebinderAutoConfiguration.class]: Post-processing of merged bean definition failed; nested exception is java.lang.IllegalStateException: Failed to introspect Class [org.springframework.cloud.context.properties.ConfigurationPropertiesBeans] from ClassLoader [jdk.internal.loader.ClassLoaders$AppClassLoader@1f89ab83]
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:579) ~[spring-beans-5.3.6.jar:5.3.6]
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:524) ~[spring-beans-5.3.6.jar:5.3.6]
	at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) ~[spring-beans-5.3.6.jar:5.3.6]
	at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.3.6.jar:5.3.6]
	at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) ~[spring-beans-5.3.6.jar:5.3.6]
	at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:213) ~[spring-beans-5.3.6.jar:5.3.6]
	at org.springframework.context.support.PostProcessorRegistrationDelegate.registerBeanPostProcessors(PostProcessorRegistrationDelegate.java:270) ~[spring-context-5.3.6.jar:5.3.6]
	at org.springframework.context.support.AbstractApplicationContext.registerBeanPostProcessors(AbstractApplicationContext.java:762) ~[spring-context-5.3.6.jar:5.3.6]
	at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:567) ~[spring-context-5.3.6.jar:5.3.6]
	at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:782) ~[spring-boot-2.4.5.jar:2.4.5]
	at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:774) ~[spring-boot-2.4.5.jar:2.4.5]
	at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:439) ~[spring-boot-2.4.5.jar:2.4.5]
	at org.springframework.boot.SpringApplication.run(SpringApplication.java:339) ~[spring-boot-2.4.5.jar:2.4.5]
	at org.springframework.boot.builder.SpringApplicationBuilder.run(SpringApplicationBuilder.java:144) ~[spring-boot-2.4.5.jar:2.4.5]
	at org.springframework.cloud.bootstrap.BootstrapApplicationListener.bootstrapServiceContext(BootstrapApplicationListener.java:212) ~[spring-cloud-context-2.2.5.RELEASE.jar:2.2.5.RELEASE]
	at org.springframework.cloud.bootstrap.BootstrapApplicationListener.onApplicationEvent(BootstrapApplicationListener.java:117) ~[spring-cloud-context-2.2.5.RELEASE.jar:2.2.5.RELEASE]
	at org.springframework.cloud.bootstrap.BootstrapApplicationListener.onApplicationEvent(BootstrapApplicationListener.java:74) ~[spring-cloud-context-2.2.5.RELEASE.jar:2.2.5.RELEASE]
	at org.springframework.context.event.SimpleApplicationEventMulticaster.doInvokeListener(SimpleApplicationEventMulticaster.java:176) ~[spring-context-5.3.6.jar:5.3.6]
	at org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:169) ~[spring-context-5.3.6.jar:5.3.6]
	at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:143) ~[spring-context-5.3.6.jar:5.3.6]
	at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:131) ~[spring-context-5.3.6.jar:5.3.6]
	at org.springframework.boot.context.event.EventPublishingRunListener.environmentPrepared(EventPublishingRunListener.java:82) ~[spring-boot-2.4.5.jar:2.4.5]
	at org.springframework.boot.SpringApplicationRunListeners.lambda$environmentPrepared$2(SpringApplicationRunListeners.java:63) ~[spring-boot-2.4.5.jar:2.4.5]
	at java.base/java.util.ArrayList.forEach(ArrayList.java:1540) ~[na:na]
	at org.springframework.boot.SpringApplicationRunListeners.doWithListeners(SpringApplicationRunListeners.java:117) ~[spring-boot-2.4.5.jar:2.4.5]
	at org.springframework.boot.SpringApplicationRunListeners.doWithListeners(SpringApplicationRunListeners.java:111) ~[spring-boot-2.4.5.jar:2.4.5]
	at org.springframework.boot.SpringApplicationRunListeners.environmentPrepared(SpringApplicationRunListeners.java:62) ~[spring-boot-2.4.5.jar:2.4.5]
	at org.springframework.boot.SpringApplication.prepareEnvironment(SpringApplication.java:375) ~[spring-boot-2.4.5.jar:2.4.5]
	at org.springframework.boot.SpringApplication.run(SpringApplication.java:333) ~[spring-boot-2.4.5.jar:2.4.5]
	at org.springframework.boot.SpringApplication.run(SpringApplication.java:1340) ~[spring-boot-2.4.5.jar:2.4.5]
	at org.springframework.boot.SpringApplication.run(SpringApplication.java:1329) ~[spring-boot-2.4.5.jar:2.4.5]
	at com.lenyuqin.product.ProductApplication.main(ProductApplication.java:14) ~[classes/:na]
Caused by: java.lang.IllegalStateException: Failed to introspect Class [org.springframework.cloud.context.properties.ConfigurationPropertiesBeans] from ClassLoader [jdk.internal.loader.ClassLoaders$AppClassLoader@1f89ab83]
	at org.springframework.util.ReflectionUtils.getDeclaredMethods(ReflectionUtils.java:481) ~[spring-core-5.3.6.jar:5.3.6]
	at org.springframework.util.ReflectionUtils.doWithLocalMethods(ReflectionUtils.java:321) ~[spring-core-5.3.6.jar:5.3.6]
	at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.buildLifecycleMetadata(InitDestroyAnnotationBeanPostProcessor.java:232) ~[spring-beans-5.3.6.jar:5.3.6]
	at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.findLifecycleMetadata(InitDestroyAnnotationBeanPostProcessor.java:210) ~[spring-beans-5.3.6.jar:5.3.6]
	at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessMergedBeanDefinition(InitDestroyAnnotationBeanPostProcessor.java:149) ~[spring-beans-5.3.6.jar:5.3.6]
	at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessMergedBeanDefinition(CommonAnnotationBeanPostProcessor.java:294) ~[spring-context-5.3.6.jar:5.3.6]
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyMergedBeanDefinitionPostProcessors(AbstractAutowireCapableBeanFactory.java:1098) ~[spring-beans-5.3.6.jar:5.3.6]
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:576) ~[spring-beans-5.3.6.jar:5.3.6]
	... 31 common frames omitted
Caused by: java.lang.NoClassDefFoundError: org/springframework/boot/context/properties/ConfigurationBeanFactoryMetadata
	at java.base/java.lang.Class.getDeclaredMethods0(Native Method) ~[na:na]
	at java.base/java.lang.Class.privateGetDeclaredMethods(Class.java:3167) ~[na:na]
	at java.base/java.lang.Class.getDeclaredMethods(Class.java:2310) ~[na:na]
	at org.springframework.util.ReflectionUtils.getDeclaredMethods(ReflectionUtils.java:463) ~[spring-core-5.3.6.jar:5.3.6]
	... 38 common frames omitted
Caused by: java.lang.ClassNotFoundException: org.springframework.boot.context.properties.ConfigurationBeanFactoryMetadata
	at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:583) ~[na:na]
	at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178) ~[na:na]
	at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521) ~[na:na]
	... 42 common frames omitted

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


相关文章

猜您喜欢

  • gateway配置nacos动态路由 配置gateway+nacos动态路由管理流程

    想了解配置gateway+nacos动态路由管理流程的相关内容吗,夏天的粽子在本文为您仔细讲解gateway配置nacos动态路由的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:gateway配置,nacos动态路由,动态路由配置,下面大家一起来学习吧。..
  • springcloud 集成nacos配置中心 spring cloud怎样集成nacos配置中心

    想了解spring cloud怎样集成nacos配置中心的相关内容吗,Insist_on_progress在本文为您仔细讲解springcloud 集成nacos配置中心的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:spring,cloud集成nacos,nacos配置中心,springcloud,nacos,下面大家一起来学习吧。..

网友评论

Copyright 2020 www.hao45.cc 【好下载】 版权所有 软件发布

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 点此查看联系方式