基于Curator操作ZooKeeper(三)-Curator整合Spring

Java原生API操作ZooKeeper可参看:

Java原生API操作Zookeeper(一)

Java原生API操作Zookeeper(二)

相关内容:

基于Curator操作ZooKeeper(一)-基本操作

基于Curator操作ZooKeeper(二)-Watcher操作-补充TreeCache

基于Curator操作ZooKeeper(二)-Watcher操作

 

Curator整合Spring和Spring Boot方式都是差不多的。

在Spring项目中引入依赖:

       

		
			org.apache.curator
			curator-framework
			4.0.0
		
		
			org.apache.curator
			curator-recipes
			4.0.0
		

增加applicationContext-xx.xml文件:




    ZK与Spring整合,启动项目时建立与ZK的连接
    
    
        
        
        
        
    

    
    
        
        
        
        
        
        
        
        
    

    
    
        
    

ZK客户端:

package dongguabai;

import org.apache.curator.framework.CuratorFramework;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Dongguabai
 * @date 2018/10/18 15:12
 */
public class ZKCurator {

    private static final Logger LOGGER = LoggerFactory.getLogger(ZKCurator.class);

    //ZK客户端
    private CuratorFramework client = null;

    public ZKCurator(CuratorFramework client) {
        this.client = client;
    }

    /**
     * 初始化操作
     */
    public void init(){
        //使用命名空间
        client  = client.usingNamespace("testDgb");
    }

    /**
     * 判断ZK是否连接
     * @return
     */
    public boolean isZKAlive(){
        return client!=null && client.isStarted();
    }
}

测试:

import dongguabai.ZKCurator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 两景Controller
 * @author Dongguabai
 * @date 2018/10/9 16:35
 */
@RestController
@RequestMapping("twoScenes")
public class ZJTwoScenesController extends BaseController{
    //todo 预留的两景Controller

    @Autowired
    private ZKCurator zkCurator;

    @RequestMapping("/check")
    public Object check(){
        return ResultHelper.success(zkCurator.isZKAlive()?"已连接":"断开");
    }
}

 

你可能感兴趣的:(zookeeper)