Android移动设备连接接入到zookeeper分布式集群
在Android Studio中添加引用依赖:
compile group:'org.apache.zookeeper', name:'zookeeper', version:'3.5.5'
Android端代码:
package zhangphil.zookeeper;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.client.ZooKeeperSaslClient;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
public class MainActivity extends AppCompatActivity {
private ZooKeeper zooKeeper;
private String DEVICE_PATH = "/devices";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//非常重要,如果没有,则Android手机客户端连接不到部署在PC上的ZooKeeper集群。
System.setProperty(ZooKeeperSaslClient.ENABLE_CLIENT_SASL_KEY,"false");
CompletableFuture.runAsync(new Runnable() {
@Override
public void run() {
try {
zk();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
private void zk() throws Exception {
zooKeeper = new ZooKeeper(getAddress(), 10 * 1000, new Watcher() {
@Override
public void process(WatchedEvent event) {
System.out.println(event.toString());
}
});
System.out.println("开始连接...");
while (!zooKeeper.getState().isConnected()) {
TimeUnit.SECONDS.sleep(3);
System.out.println("尝试连接...");
}
System.out.println("连接建立");
login();
synchronized (this) {
wait();
}
}
private void login() throws Exception {
//创建节点。
String path = zooKeeper.create(DEVICE_PATH + "/client", "ip:127.0.0.1".getBytes("UTF-8"), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
byte[] data = zooKeeper.getData(path, null, null);
System.out.println(path + " => " + new String(data));
System.out.println("注册设备成功");
}
private String getAddress() {
String ip = "192.168.137.1";
return ip + ":2181," + ip + ":2182," + ip + ":2183";
}
}
需要保证Android手机与PC上部署的ZooKeeper集群连通,比如,可以让Android手机与PC同处于一个局域网(共同连接到一个WIFI)。
特别注意,在Android手机上跑的ZooKeeper程序,必须显示的关闭SASL认证,否则Android手机上的Zookeeper客户端连接不到处于PC网络的ZooKeeper集群。关闭SASL其实就一行代码:
System.setProperty(ZooKeeperSaslClient.ENABLE_CLIENT_SASL_KEY,"false");
接下来运行系统。首先要启动位于PC网络的ZooKeeper集群。
在Android手机上跑起上面的程序代码输出:
然后在PC上,通过命令行ls查询:
说明Android手机接入ZooKeeper成功。
这很有趣,一旦这条路走通,就意味着可以使用ZooKeeper做非常棒的Android设备在集群中的分布式系统应用,如,实时检测大规模集群中,某一Android设备是否在线,即心跳。