ZookeeperConfig.java 1.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
package com.kwan.shuyu.config;


import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * zookeeper的配置类
 *
 * @author : qinyingjie
 * @version : 2.2.0
 * @date : 2023/5/10 12:37
 */
@Configuration
public class ZookeeperConfig {

    @Value("${kwan.zookeeper.hostlist}")
    private String hostlist;

    @Bean(destroyMethod = "close")
    public CuratorFramework connect() {
        /*
         *
         * @param connectString       连接字符串。zk server 地址和端口 "120.79.36.53:2181,120.79.36.53:2182,120.79.36.53:2183"
         * @param sessionTimeoutMs    会话超时时间 单位ms
         * @param connectionTimeoutMs 连接超时时间 单位ms
         * @param retryPolicy         重试策略
         */
       /* //重试策略
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(3000,10);
        //1.第一种方式
        CuratorFramework client = CuratorFrameworkFactory.newClient("120.79.36.53:2181,120.79.36.53:2182,120.79.36.53:2183",
                60 * 1000, 15 * 1000, retryPolicy);*/
        //重试策略
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(3000, 10);
        //2.第二种方式
        CuratorFramework client = CuratorFrameworkFactory.builder()
                .connectString(hostlist)
                .sessionTimeoutMs(60 * 1000)
                .connectionTimeoutMs(15 * 1000)
                .retryPolicy(retryPolicy)
                .namespace("itheima")
                .build();
        //开启连接
        client.start();
        return client;
    }
}