Nacos dynamic routing configuration in springboot

Nacos dynamic routing in springboot

Don’t say anything, if springboot-nacos doesn’t understand, let’s learn by myself. I’ll post the code directly! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! !

Insert picture description here

first of all. . .

I have a server myself. The code written when I am bored mainly calls the interface through the gateway, so I have the following code.
1. As a dynamic routing maintenance management class
@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. Dynamic configuration routing service based on 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

Insert picture description here

4. Nacos gateway configuration

Insert picture description here

5. Finally: I built the two services of the father and son project after sending them to the server

Pay attention!!!: Be sure to turn on the firewall, log on to Alibaba Cloud's own service to increase the port, and then increase the port in Linux

Linux firewall related commands

Delete firewall-cmd --zone= public --remove-port=80/tcp --permanent
open firewall-cmd --zone=public --add-port=1935/tcp --permanent
view status systemctl status firewalld
start systemctl start firewalld
view the opened ports firewall-cmd --list-ports
restart firewall-cmd --reload There is a port in the yml configuration file. This also needs to be opened on Alibaba
Insert picture description here
Cloud.
This is the gateway port number for interface access.
Insert picture description here

Ok, this article is here, recording life. Record technology, hope to help you all, bye!

Insert picture description here

Guess you like

Origin blog.csdn.net/m0_46379371/article/details/113247647