• springboot项目启动后do something


    第一种方法:

    利用CommandLineRunner接口,自定义接口实现类,并用@Component标注。CommandLineRunner接口在spring-boot.jar中,只有一个run方法,可在run方法中写我们的业务逻辑,不管是初始化一些连接还是预热数据。

    示例如下:

    @Component
    @Order(0)
    public class ZookeeperConnector implements CommandLineRunner {
        @Value("${server.weight}")
        private int weight;
    
        @Value("${server.port}")
        private int port;
    
        @Value("${zookeeper.url}")
        private String zookeeperUrl;
    
        @Override
        public void run(String... args) throws Exception {
            RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
            CuratorFramework client = CuratorFrameworkFactory.newClient(zookeeperUrl, 5000, 3000, retryPolicy);
            client.start();
            String ip = "127.0.0.1";
            String hostAndPort = ip + ":" + port;
            String path = "/server1/" + hostAndPort;
            try {
                if (client.checkExists().forPath(path) != null) {
                    client.delete().forPath(path);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            client.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL)
                    .forPath(path, String.valueOf(weight).getBytes(StandardCharsets.UTF_8));
        }
    }

    第二种方法:

  • 相关阅读:
    eNSP模拟器的路由器无法启动
    Centos7环境下的root账号不能开启VLC
    curl 静态库编译 非https
    Javascript进阶
    区块链 2.0
    Javascript基础
    9 信号量和管程
    Java基础笔记
    Go笔记
    10 死锁
  • 原文地址:https://www.cnblogs.com/koushr/p/11779231.html
Copyright © 2020-2023  润新知