zoukankan      html  css  js  c++  java
  • 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));
        }
    }

    第二种方法:

  • 相关阅读:
    wsl安装torch-0.4.0 cpu版本
    基于TimeLine编辑角色动画(三)
    unity在Game窗口绘制网格Capsule
    unityGame窗口绘制Box
    unity在Game窗口绘制网格球
    读取Excal数据通过反射赋值
    根据Excal表生成代码
    状态模式设计动画状态机
    第三人称相机
    Nhibernate配置MySQL踩坑记录
  • 原文地址:https://www.cnblogs.com/koushr/p/11779231.html
Copyright © 2011-2022 走看看