第一种方法:
利用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)); } }
第二种方法: