Scala Zookeeper 訪問 Demo

import scala.collection.mutable.ArrayBuffer
import scala.collection.JavaConverters._

import com.google.common.base.{Objects, Strings}
import org.apache.commons.compress.utils.Charsets
import org.apache.curator.framework.{CuratorFramework, CuratorFrameworkFactory}
import org.apache.curator.retry.ExponentialBackoffRetry
import org.apache.curator.utils.ZKPaths
import org.slf4j.LoggerFactory

object ZkTest {
  private[this] val logger = LoggerFactory.getLogger(classOf[ZkTest])
  private[this] val zkAddress = "localhost:2181"

  private[this] var client: CuratorFramework = _

  def init(zkAddr: String = zkAddress): Unit = {
    client = CuratorFrameworkFactory.newClient(
      zkAddr,
      new ExponentialBackoffRetry(1000, 3)
    )

    client.start()
  }

  def destroy(): Unit = {
    if (client != null) {
      client.close()
    }

  }

  /**
   * 給定一個ZK的路徑,返回路徑下所有< 目錄, 值 > 的對象數組
   * @param path
   * @return
   */
  def findProperties(path: String): Array[PropertyItem] = {
    val properties = new ArrayBuffer[PropertyItem]()

    val stat = client.checkExists().forPath(path)
    if (null != stat) {
      val children = client.getChildren.forPath(path).asScala
      val dataBuilder = client.getData
      if (children != null) for (child <- children) {
        val propPath = ZKPaths.makePath(path, child)
        val item = PropertyItem(child, new String(dataBuilder.forPath(propPath), Charsets.UTF_8))
        properties += item
      }
    }

    properties.toArray
  }

  /**
   * 給定一個ZK路徑,返回路徑下所有子目錄名字的數組
   * @param path
   * @return
   */
  def listChildren(path: String): Array[String] = {
    var children = Array.empty[String]
    val stat = client.checkExists.forPath(path)

    if (stat != null) {
      val childrenBuilder = client.getChildren
      children = childrenBuilder.forPath(path).asScala.toArray
    }
    children
  }

  /**
   * 創建ZK節點,返回創建狀態
   * @param path
   * @param value
   * @return
   */
  def createProperty(path: String, value: String = null): Boolean = {
    var result = false

    try {
      val stat = client.checkExists.forPath(path)
      if (stat == null) {
        val data = if (Strings.isNullOrEmpty(value)) {
          Array.empty[Byte]
        } else {
          value.getBytes(Charsets.UTF_8)
        }
        val opResult = client.create.creatingParentsIfNeeded.forPath(path, data)
        result = Objects.equal(path, opResult)
      }
    } catch {
      case e: Exception =>
        logger.error(e.getMessage, e)
    }
    result
  }

  /**
   * 更新節點數據
   * @param path
   * @param value
   * @return
   */
  def updateProperty(path: String, value: String): Boolean = {
    var result = false
    try {
      val stat = client.checkExists.forPath(path)
      if (stat != null) {
        val opResult = client.setData().forPath(path, value.getBytes(Charsets.UTF_8))
        result = opResult != null
      }
      else {
        val opResult = client.create.creatingParentsIfNeeded.forPath(path, value.getBytes(Charsets.UTF_8))
        result = Objects.equal(path, opResult)
      }
    } catch {
      case e: Exception =>
        logger.error(e.getMessage, e)
    }
    result
  }

  /**
   * 刪除節點
   * @param path
   */
  def deleteProperty(path: String): Unit = {
    try {
      val stat = client.checkExists.forPath(path)
      if (stat != null) {
        client.delete.deletingChildrenIfNeeded.forPath(path)
      }
    } catch {
      case e: Exception =>
        logger.error(e.getMessage, e)
    }
  }

  /**
   * 獲取節點數據
   * @param path
   * @return
   */
  def getValue(path: String): String = {
    var result: String = null
    try {
      val stat = client.checkExists.forPath(path)
      if (stat != null) {
        val data = client.getData.forPath(path)
        result = new String(data)
      } 
    } catch {
      case e: Exception =>
        logger.error(e.getMessage, e)
    }
    result
  }

}

class ZkTest

case class PropertyItem(name: String, value: String)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章