以 zk3.6.1 为例
1. 根据 id:password 生成 digest
import org.apache.zookeeper.server.auth.DigestAuthenticationProvider;
import java.security.NoSuchAlgorithmException;
public class ZookeeperSuperUser {
public static void main(String[] args) throws NoSuchAlgorithmException {
String m = DigestAuthenticationProvider.generateDigest("super:shogun");
System.out.println(m);
}
}
//super:KF7G9HXutwzAB4FvCxKCxjKAUTY=
zkServer.sh start 方法配置变量
添加
"-Dzookeeper.DigestAuthenticationProvider.superDigest=super:KF7G9HXutwzAB4FvCxKCxjKAUTY="到 start 方法
case $1 in
start)
echo -n "Starting zookeeper ... "
if [ -f "$ZOOPIDFILE" ]; then
if kill -0 `cat "$ZOOPIDFILE"` > /dev/null 2>&1; then
echo $command already running as process `cat "$ZOOPIDFILE"`.
exit 1
fi
fi
nohup "$JAVA" $ZOO_DATADIR_AUTOCREATE "-Dzookeeper.log.dir=${ZOO_LOG_DIR}" \
"-Dzookeeper.log.file=${ZOO_LOG_FILE}" "-Dzookeeper.root.logger=${ZOO_LOG4J_PROP}" \
"-Dzookeeper.DigestAuthenticationProvider.superDigest=super:KF7G9HXutwzAB4FvCxKCxjKAUTY=" \
-XX:+HeapDumpOnOutOfMemoryError -XX:OnOutOfMemoryError='kill -9 %p' \
-cp "$CLASSPATH" $JVMFLAGS $ZOOMAIN "$ZOOCFG" > "$_ZOO_DAEMON_OUT" 2>&1 < /dev/null &
if [ $? -eq 0 ]
then
case "$OSTYPE" in
*solaris*)
/bin/echo "${!}\\c" > "$ZOOPIDFILE"
;;
*)
/bin/echo -n $! > "$ZOOPIDFILE"
;;
esac
if [ $? -eq 0 ];
then
sleep 1
pid=$(cat "${ZOOPIDFILE}")
if ps -p "${pid}" > /dev/null 2>&1; then
echo STARTED
else
echo FAILED TO START
exit 1
fi
else
echo FAILED TO WRITE PID
exit 1
fi
else
echo SERVER DID NOT START
exit 1
fi
;;
3. zkServer.sh restart
4. 代码中使用
String connectString = "127.0.0.1:2181";
// Create ZooKeeper client
ZooKeeper zooKeeper = new ZooKeeper(connectString, 3000, watcher);
// Add digest authentication information
zooKeeper.addAuthInfo("digest", "super:shogun".getBytes());
5. zkCli 中使用
[zk: localhost:2181(CONNECTED) 1] ls /a/acl-ip1
Authentication is not valid : /a/acl-ip1
[zk: localhost:2181(CONNECTED) 2] addauth digest super:shogun
[zk: localhost:2181(CONNECTED) 3] ls /a/acl-ip1
[]