├── README.md ├── zookeeper-client-example ├── src │ ├── test │ │ ├── resources │ │ │ ├── config.properties │ │ │ └── spring-config.xml │ │ └── java │ │ │ └── com │ │ │ └── github │ │ │ └── loafer │ │ │ └── rpc │ │ │ ├── ServiceType.java │ │ │ ├── ExampleService.java │ │ │ ├── ExampleServiceImpl.java │ │ │ └── ServiceDiscoveryTest.java │ └── main │ │ └── java │ │ └── com │ │ └── github │ │ └── loafer │ │ └── rpc │ │ ├── ServiceRegistry.java │ │ ├── ServiceRegisterException.java │ │ ├── annotation │ │ ├── ServiceProviders.java │ │ └── ServiceProvider.java │ │ ├── ServiceInstance.java │ │ ├── ServiceDiscovery.java │ │ └── ServiceRegistryImpl.java └── pom.xml ├── .gitignore ├── zookeeper-offical-client ├── src │ └── test │ │ └── java │ │ └── com │ │ └── github │ │ └── loafer │ │ ├── zookeeper │ │ ├── service │ │ │ ├── Constant.java │ │ │ ├── ServiceOne.java │ │ │ └── ServiceTwo.java │ │ └── groupmembership │ │ │ ├── ServiceOneNode1.java │ │ │ ├── ServiceOneNode2.java │ │ │ └── ServiceOneClusterTest.java │ │ ├── ServiceDiscoveryTest.java │ │ ├── EphemeralNodeTest.java │ │ ├── ServiceDiscovery.java │ │ ├── ExampleTest.java │ │ ├── WatchZnodeTest.java │ │ └── BasicOperationForClient.java └── pom.xml ├── master-worker-example ├── src │ ├── test │ │ └── java │ │ │ └── com │ │ │ └── github │ │ │ └── loafer │ │ │ ├── workers │ │ │ └── Workers.java │ │ │ ├── ClientTest.java │ │ │ └── master │ │ │ ├── MasterOne.java │ │ │ └── MasterTwo.java │ └── main │ │ └── java │ │ └── com │ │ └── github │ │ └── loafer │ │ └── zookeeper │ │ └── example │ │ ├── Client.java │ │ ├── Worker.java │ │ └── Master.java └── pom.xml ├── netty-example ├── src │ ├── main │ │ └── java │ │ │ └── com │ │ │ └── github │ │ │ └── loafer │ │ │ ├── timer │ │ │ ├── TimerEncoder.java │ │ │ ├── UnixTime.java │ │ │ ├── TimerDecoder.java │ │ │ ├── TimerClinetHandler.java │ │ │ ├── TimerServerHandler.java │ │ │ ├── TimerClient.java │ │ │ └── TimerServer.java │ │ │ ├── discard │ │ │ ├── DiscardServerHandler.java │ │ │ └── DiscardServer.java │ │ │ ├── echo │ │ │ ├── EchoServerHandler.java │ │ │ ├── EchoClientHandler.java │ │ │ ├── EchoServer.java │ │ │ └── EchoClient.java │ │ │ └── sample │ │ │ ├── SimpleChannelHandler.java │ │ │ └── SampleNettyServer.java │ └── test │ │ └── java │ │ └── com │ │ └── github │ │ └── loafer │ │ └── channelhandler │ │ ├── FirstChannelHandler.java │ │ ├── SecondChannelHandler.java │ │ ├── ThirdChannelHandler.java │ │ └── EchoServer.java └── pom.xml └── curator-example ├── pom.xml └── src └── test └── java └── com └── github └── loafer └── curator └── CuratorTest.java /README.md: -------------------------------------------------------------------------------- 1 | # zookeeper-tutorials 2 | -------------------------------------------------------------------------------- /zookeeper-client-example/src/test/resources/config.properties: -------------------------------------------------------------------------------- 1 | registry.address=192.168.56.120:2181 -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | *.ipr 3 | *.iws 4 | .idea/ 5 | target/ 6 | pom.xml.tag 7 | pom.xml.releaseBackup 8 | pom.xml.versionsBackup 9 | pom.xml.next 10 | release.properties 11 | -------------------------------------------------------------------------------- /zookeeper-client-example/src/test/java/com/github/loafer/rpc/ServiceType.java: -------------------------------------------------------------------------------- 1 | package com.github.loafer.rpc; 2 | 3 | /** 4 | * @author zhaojh. 5 | */ 6 | public enum ServiceType { 7 | RPC, HTTPAPI 8 | } 9 | -------------------------------------------------------------------------------- /zookeeper-client-example/src/test/java/com/github/loafer/rpc/ExampleService.java: -------------------------------------------------------------------------------- 1 | package com.github.loafer.rpc; 2 | 3 | /** 4 | * @author zhaojh. 5 | */ 6 | public interface ExampleService { 7 | String sayHello(String name); 8 | } 9 | -------------------------------------------------------------------------------- /zookeeper-client-example/src/main/java/com/github/loafer/rpc/ServiceRegistry.java: -------------------------------------------------------------------------------- 1 | package com.github.loafer.rpc; 2 | 3 | /** 4 | * @author zhaojh. 5 | */ 6 | public interface ServiceRegistry { 7 | void registerService(ServiceInstance serviceInstance) throws Exception; 8 | } 9 | -------------------------------------------------------------------------------- /zookeeper-offical-client/src/test/java/com/github/loafer/zookeeper/service/Constant.java: -------------------------------------------------------------------------------- 1 | package com.github.loafer.zookeeper.service; 2 | 3 | /** 4 | * @author zhaojh. 5 | */ 6 | public class Constant { 7 | public static final String CONNECTION_STRING = "192.168.56.120:2181/NameService"; 8 | // public static final String ZK_SERVICE_REGISTRY_PATH = "/NameService"; 9 | public static final int SESSION_TIMEOUT = 2000; 10 | } 11 | -------------------------------------------------------------------------------- /master-worker-example/src/test/java/com/github/loafer/workers/Workers.java: -------------------------------------------------------------------------------- 1 | package com.github.loafer.workers; 2 | 3 | import com.github.loafer.zookeeper.example.Worker; 4 | 5 | /** 6 | * @author zhaojh. 7 | */ 8 | public class Workers { 9 | public static void main(String[] args){ 10 | for (int i=1; i<=2; i++){ 11 | Thread thread = new Thread(new Worker("192.168.56.120:2181/master-workers/workers")); 12 | thread.start(); 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /zookeeper-client-example/src/main/java/com/github/loafer/rpc/ServiceRegisterException.java: -------------------------------------------------------------------------------- 1 | package com.github.loafer.rpc; 2 | 3 | import org.springframework.beans.BeansException; 4 | 5 | /** 6 | * @author zhaojh. 7 | */ 8 | public class ServiceRegisterException extends BeansException { 9 | 10 | public ServiceRegisterException(String msg) { 11 | super(msg); 12 | } 13 | 14 | public ServiceRegisterException(String msg, Throwable cause) { 15 | super(msg, cause); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /zookeeper-client-example/src/main/java/com/github/loafer/rpc/annotation/ServiceProviders.java: -------------------------------------------------------------------------------- 1 | package com.github.loafer.rpc.annotation; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | 8 | /** 9 | * @author zhaojh. 10 | */ 11 | @Target(ElementType.TYPE) 12 | @Retention(RetentionPolicy.RUNTIME) 13 | public @interface ServiceProviders { 14 | ServiceProvider[] value(); 15 | } 16 | -------------------------------------------------------------------------------- /netty-example/src/main/java/com/github/loafer/timer/TimerEncoder.java: -------------------------------------------------------------------------------- 1 | package com.github.loafer.timer; 2 | 3 | import io.netty.buffer.ByteBuf; 4 | import io.netty.channel.ChannelHandlerContext; 5 | import io.netty.handler.codec.MessageToByteEncoder; 6 | 7 | /** 8 | * @author zhaojh. 9 | */ 10 | public class TimerEncoder extends MessageToByteEncoder{ 11 | @Override 12 | protected void encode(ChannelHandlerContext ctx, UnixTime msg, ByteBuf out) throws Exception { 13 | out.writeInt(msg.value()); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /zookeeper-client-example/src/test/java/com/github/loafer/rpc/ExampleServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.github.loafer.rpc; 2 | 3 | import com.github.loafer.rpc.annotation.ServiceProvider; 4 | 5 | /** 6 | * @author zhaojh. 7 | */ 8 | @ServiceProvider( 9 | name = "HelloService", 10 | type = ExampleService.class, 11 | description = "Hello Service" 12 | ) 13 | public class ExampleServiceImpl implements ExampleService { 14 | @Override 15 | public String sayHello(String name) { 16 | return String.format("Hello %s", name); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /master-worker-example/src/test/java/com/github/loafer/ClientTest.java: -------------------------------------------------------------------------------- 1 | package com.github.loafer; 2 | 3 | import com.github.loafer.zookeeper.example.Client; 4 | 5 | import java.io.IOException; 6 | 7 | /** 8 | * @author zhaojh. 9 | */ 10 | public class ClientTest { 11 | public static void main(String[] args) throws IOException, InterruptedException { 12 | Client client = new Client("192.168.56.120:2181/master-workers/tasks"); 13 | client.startZK(); 14 | 15 | client.queueCommand("cmd"); 16 | System.in.read(); 17 | client.stopZK(); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /zookeeper-client-example/src/main/java/com/github/loafer/rpc/annotation/ServiceProvider.java: -------------------------------------------------------------------------------- 1 | package com.github.loafer.rpc.annotation; 2 | 3 | import org.springframework.stereotype.Component; 4 | 5 | import java.lang.annotation.ElementType; 6 | import java.lang.annotation.Retention; 7 | import java.lang.annotation.RetentionPolicy; 8 | import java.lang.annotation.Target; 9 | 10 | /** 11 | * @author zhaojh. 12 | */ 13 | @Target(ElementType.TYPE) 14 | @Retention(RetentionPolicy.RUNTIME) 15 | @Component 16 | public @interface ServiceProvider { 17 | String name(); 18 | Class type(); 19 | String description() default ""; 20 | } 21 | -------------------------------------------------------------------------------- /master-worker-example/src/test/java/com/github/loafer/master/MasterOne.java: -------------------------------------------------------------------------------- 1 | package com.github.loafer.master; 2 | 3 | import com.github.loafer.zookeeper.example.Master; 4 | 5 | import java.io.IOException; 6 | 7 | /** 8 | * @author zhaojh. 9 | */ 10 | public class MasterOne { 11 | public static void main(String[] args) throws IOException, InterruptedException { 12 | Master master = new Master("192.168.56.120:2181/master-workers", "Master One"); 13 | 14 | master.startZK(); 15 | 16 | master.bootstrap(); 17 | 18 | master.runForMaster(); 19 | 20 | System.in.read(); 21 | master.stopZK(); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /master-worker-example/src/test/java/com/github/loafer/master/MasterTwo.java: -------------------------------------------------------------------------------- 1 | package com.github.loafer.master; 2 | 3 | import com.github.loafer.zookeeper.example.Master; 4 | 5 | import java.io.IOException; 6 | 7 | /** 8 | * @author zhaojh. 9 | */ 10 | public class MasterTwo { 11 | public static void main(String[] args) throws IOException, InterruptedException { 12 | Master master = new Master("192.168.56.120:2181/master-workers", "Master Two"); 13 | 14 | master.startZK(); 15 | 16 | master.bootstrap(); 17 | 18 | master.runForMaster(); 19 | 20 | System.in.read(); 21 | master.stopZK(); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /netty-example/src/main/java/com/github/loafer/timer/UnixTime.java: -------------------------------------------------------------------------------- 1 | package com.github.loafer.timer; 2 | 3 | import java.util.Date; 4 | 5 | /** 6 | * @author zhaojh. 7 | */ 8 | public class UnixTime { 9 | private final int value; 10 | 11 | public UnixTime(int value) { 12 | this.value = value; 13 | } 14 | 15 | public UnixTime(){ 16 | this.value = (int) (System.currentTimeMillis()/1000L + 2208988800L); 17 | } 18 | 19 | public int value() { 20 | return value; 21 | } 22 | 23 | @Override 24 | public String toString() { 25 | return new Date((value() - 2208988800L) * 1000L).toString(); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /zookeeper-client-example/src/test/java/com/github/loafer/rpc/ServiceDiscoveryTest.java: -------------------------------------------------------------------------------- 1 | package com.github.loafer.rpc; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.test.context.ContextConfiguration; 6 | import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 7 | 8 | import java.io.IOException; 9 | 10 | /** 11 | * @author zhaojh. 12 | */ 13 | @RunWith(SpringJUnit4ClassRunner.class) 14 | @ContextConfiguration({"/spring-config.xml"}) 15 | public class ServiceDiscoveryTest { 16 | 17 | @Test 18 | public void testServiceRegister() throws IOException { 19 | System.in.read(); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /netty-example/src/main/java/com/github/loafer/timer/TimerDecoder.java: -------------------------------------------------------------------------------- 1 | package com.github.loafer.timer; 2 | 3 | import io.netty.buffer.ByteBuf; 4 | import io.netty.channel.ChannelHandlerContext; 5 | import io.netty.handler.codec.ByteToMessageDecoder; 6 | 7 | import java.util.List; 8 | 9 | /** 10 | * @author zhaojh. 11 | */ 12 | public class TimerDecoder extends ByteToMessageDecoder { 13 | @Override 14 | protected void decode(ChannelHandlerContext ctx, ByteBuf in, List out) throws Exception { 15 | if(in.readableBytes()<4){ 16 | return; 17 | } 18 | 19 | // out.add(in.readBytes(4)); 20 | out.add(new UnixTime(in.readInt())); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /netty-example/src/test/java/com/github/loafer/channelhandler/FirstChannelHandler.java: -------------------------------------------------------------------------------- 1 | package com.github.loafer.channelhandler; 2 | 3 | import io.netty.channel.ChannelHandlerContext; 4 | import io.netty.channel.ChannelInboundHandlerAdapter; 5 | import io.netty.util.ReferenceCountUtil; 6 | 7 | /** 8 | * @author zhaojh. 9 | */ 10 | public class FirstChannelHandler extends ChannelInboundHandlerAdapter { 11 | @Override 12 | public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { 13 | try{ 14 | System.out.println("FirstChannelHandler received: " + msg); 15 | ctx.fireChannelRead(msg); 16 | }finally { 17 | ReferenceCountUtil.release(msg); 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /netty-example/src/test/java/com/github/loafer/channelhandler/SecondChannelHandler.java: -------------------------------------------------------------------------------- 1 | package com.github.loafer.channelhandler; 2 | 3 | import io.netty.buffer.ByteBuf; 4 | import io.netty.buffer.ByteBufUtil; 5 | import io.netty.channel.ChannelHandlerContext; 6 | import io.netty.channel.SimpleChannelInboundHandler; 7 | import io.netty.util.ReferenceCountUtil; 8 | 9 | /** 10 | * @author zhaojh. 11 | */ 12 | public class SecondChannelHandler extends SimpleChannelInboundHandler { 13 | @Override 14 | protected void channelRead0(ChannelHandlerContext ctx, 15 | ByteBuf msg) throws Exception { 16 | System.out.println("SecondChannelHandler received: " + ByteBufUtil.hexDump(msg.readBytes(msg.readableBytes()))); 17 | ctx.fireChannelRead(msg); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /zookeeper-offical-client/src/test/java/com/github/loafer/ServiceDiscoveryTest.java: -------------------------------------------------------------------------------- 1 | package com.github.loafer; 2 | 3 | import java.io.IOException; 4 | import java.util.Scanner; 5 | 6 | /** 7 | * @author zhaojh. 8 | */ 9 | public class ServiceDiscoveryTest { 10 | public static void main(String[] args) throws IOException { 11 | ServiceDiscovery discovery = new ServiceDiscovery(); 12 | 13 | Scanner scanner = new Scanner(System.in); 14 | System.out.println("请输入'quit'结束程序:"); 15 | while (true){ 16 | String commond = scanner.nextLine(); 17 | if(commond.equalsIgnoreCase("quit")){ 18 | System.out.println("bye!"); 19 | break; 20 | } 21 | System.out.println(">>" + commond); 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /zookeeper-offical-client/src/test/java/com/github/loafer/zookeeper/groupmembership/ServiceOneNode1.java: -------------------------------------------------------------------------------- 1 | package com.github.loafer.zookeeper.groupmembership; 2 | 3 | import com.github.loafer.zookeeper.service.ServiceOne; 4 | 5 | import java.io.IOException; 6 | import java.util.Scanner; 7 | 8 | /** 9 | * @author zhaojh. 10 | */ 11 | public class ServiceOneNode1 { 12 | public static void main(String[] args) throws IOException { 13 | ServiceOne serviceOne = new ServiceOne(); 14 | 15 | Scanner scanner = new Scanner(System.in); 16 | System.out.println("[ServiceOneNode1]请输入'quit'结束程序:"); 17 | while (true){ 18 | String commond = scanner.nextLine(); 19 | if(commond.equalsIgnoreCase("quit")){ 20 | System.out.println("bye!"); 21 | break; 22 | } 23 | System.out.println(">>" + commond); 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /zookeeper-offical-client/src/test/java/com/github/loafer/zookeeper/groupmembership/ServiceOneNode2.java: -------------------------------------------------------------------------------- 1 | package com.github.loafer.zookeeper.groupmembership; 2 | 3 | import com.github.loafer.zookeeper.service.ServiceOne; 4 | 5 | import java.io.IOException; 6 | import java.util.Scanner; 7 | 8 | /** 9 | * @author zhaojh. 10 | */ 11 | public class ServiceOneNode2 { 12 | public static void main(String[] args) throws IOException { 13 | ServiceOne serviceOne = new ServiceOne(); 14 | 15 | Scanner scanner = new Scanner(System.in); 16 | System.out.println("[ServiceOneNode1]请输入'quit'结束程序:"); 17 | while (true){ 18 | String commond = scanner.nextLine(); 19 | if(commond.equalsIgnoreCase("quit")){ 20 | System.out.println("bye!"); 21 | break; 22 | } 23 | System.out.println(">>" + commond); 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /netty-example/src/main/java/com/github/loafer/discard/DiscardServerHandler.java: -------------------------------------------------------------------------------- 1 | package com.github.loafer.discard; 2 | 3 | import io.netty.buffer.ByteBuf; 4 | import io.netty.channel.ChannelHandlerContext; 5 | import io.netty.channel.ChannelInboundHandlerAdapter; 6 | import io.netty.util.CharsetUtil; 7 | import io.netty.util.ReferenceCountUtil; 8 | 9 | /** 10 | * @author zhaojh. 11 | */ 12 | public class DiscardServerHandler extends ChannelInboundHandlerAdapter { 13 | @Override 14 | public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { 15 | try { 16 | ByteBuf in = (ByteBuf) msg; 17 | System.out.println(in.toString(CharsetUtil.US_ASCII)); 18 | }finally { 19 | ReferenceCountUtil.release(msg); 20 | } 21 | } 22 | 23 | @Override 24 | public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { 25 | cause.printStackTrace(); 26 | ctx.close(); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /netty-example/src/main/java/com/github/loafer/echo/EchoServerHandler.java: -------------------------------------------------------------------------------- 1 | package com.github.loafer.echo; 2 | 3 | import io.netty.buffer.ByteBuf; 4 | import io.netty.channel.ChannelHandlerContext; 5 | import io.netty.channel.ChannelInboundHandlerAdapter; 6 | import io.netty.util.CharsetUtil; 7 | 8 | /** 9 | * @author zhaojh. 10 | */ 11 | public class EchoServerHandler extends ChannelInboundHandlerAdapter { 12 | @Override 13 | public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { 14 | ByteBuf in = (ByteBuf) msg; 15 | System.out.println("Received: " + in.toString(CharsetUtil.US_ASCII)); 16 | ctx.write(msg); 17 | } 18 | 19 | @Override 20 | public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { 21 | ctx.flush(); 22 | } 23 | 24 | @Override 25 | public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { 26 | cause.printStackTrace(); 27 | ctx.close(); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /zookeeper-client-example/src/test/resources/spring-config.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | 9 | 10 | 11 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /zookeeper-offical-client/src/test/java/com/github/loafer/zookeeper/groupmembership/ServiceOneClusterTest.java: -------------------------------------------------------------------------------- 1 | package com.github.loafer.zookeeper.groupmembership; 2 | 3 | import com.github.loafer.zookeeper.service.ServiceOne; 4 | 5 | import java.io.IOException; 6 | import java.util.Scanner; 7 | 8 | /** 9 | * @author zhaojh. 10 | */ 11 | public class ServiceOneClusterTest { 12 | 13 | public static void main(String[] args) throws IOException { 14 | ServiceOne serviceOneNode1 = new ServiceOne(); 15 | ServiceOne serviceOneNode2 = new ServiceOne(); 16 | ServiceOne serviceOneNode3 = new ServiceOne(); 17 | 18 | 19 | 20 | Scanner scanner = new Scanner(System.in); 21 | System.out.println("请输入'quit'结束程序:"); 22 | while (true){ 23 | String commond = scanner.nextLine(); 24 | if(commond.equalsIgnoreCase("quit")){ 25 | System.out.println("bye!"); 26 | break; 27 | } 28 | System.out.println(">>" + commond); 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /curator-example/pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | 5 | com.github.loafer 6 | curator-example 7 | 1.0-SNAPSHOT 8 | jar 9 | 10 | curator-example 11 | http://maven.apache.org 12 | 13 | 14 | UTF-8 15 | 16 | 17 | 18 | 19 | org.apache.curator 20 | curator-framework 21 | 2.7.1 22 | 23 | 24 | 25 | junit 26 | junit 27 | 4.11 28 | test 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /zookeeper-client-example/src/main/java/com/github/loafer/rpc/ServiceInstance.java: -------------------------------------------------------------------------------- 1 | package com.github.loafer.rpc; 2 | 3 | import com.fasterxml.jackson.annotation.JsonIgnore; 4 | 5 | /** 6 | * @author zhaojh. 7 | */ 8 | public class ServiceInstance { 9 | private String name; 10 | private Class classType; 11 | private String description; 12 | private Object instance; 13 | private String address; 14 | private int port; 15 | 16 | public ServiceInstance(String name, Object instance) { 17 | this.name = name; 18 | this.instance = instance; 19 | } 20 | 21 | public String getName() { 22 | return name; 23 | } 24 | 25 | public Class getClassType() { 26 | return classType; 27 | } 28 | 29 | public void setClassType(Class classType) { 30 | this.classType = classType; 31 | } 32 | 33 | public String getDescription() { 34 | return description; 35 | } 36 | 37 | public void setDescription(String description) { 38 | this.description = description; 39 | } 40 | 41 | @JsonIgnore 42 | public Object getInstance() { 43 | return instance; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /zookeeper-offical-client/pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | 5 | com.github.loafer 6 | zookeeper-offical-client 7 | 1.0-SNAPSHOT 8 | 9 | pom 10 | 11 | zookeeper-offical-client 12 | http://maven.apache.org 13 | 14 | 15 | UTF-8 16 | 17 | 18 | 19 | 20 | org.apache.zookeeper 21 | zookeeper 22 | 3.4.6 23 | 24 | 25 | junit 26 | junit 27 | 4.11 28 | test 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /zookeeper-offical-client/src/test/java/com/github/loafer/zookeeper/service/ServiceOne.java: -------------------------------------------------------------------------------- 1 | package com.github.loafer.zookeeper.service; 2 | 3 | import static com.github.loafer.zookeeper.service.Constant.*; 4 | 5 | import org.apache.zookeeper.*; 6 | 7 | import java.io.IOException; 8 | 9 | /** 10 | * @author zhaojh. 11 | */ 12 | public class ServiceOne implements Watcher{ 13 | private static final String SERVICE_NAME = "/serviceOne"; 14 | private ZooKeeper zk; 15 | 16 | public ServiceOne() throws IOException { 17 | zk = new ZooKeeper(CONNECTION_STRING, SESSION_TIMEOUT, this); 18 | } 19 | 20 | @Override 21 | public void process(WatchedEvent event) { 22 | if(event.getState() == Event.KeeperState.SyncConnected){ 23 | registSelf(); 24 | } 25 | } 26 | 27 | private void registSelf(){ 28 | try { 29 | zk.create(SERVICE_NAME, "service one".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL); 30 | } catch (KeeperException e) { 31 | e.printStackTrace(); 32 | } catch (InterruptedException e) { 33 | e.printStackTrace(); 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /zookeeper-offical-client/src/test/java/com/github/loafer/zookeeper/service/ServiceTwo.java: -------------------------------------------------------------------------------- 1 | package com.github.loafer.zookeeper.service; 2 | 3 | import org.apache.zookeeper.*; 4 | 5 | import java.io.IOException; 6 | 7 | import static com.github.loafer.zookeeper.service.Constant.*; 8 | 9 | /** 10 | * @author zhaojh. 11 | */ 12 | public class ServiceTwo implements Watcher{ 13 | private static final String SERVICE_NAME = "/serviceTwo"; 14 | private ZooKeeper zk; 15 | 16 | public ServiceTwo() throws IOException { 17 | zk = new ZooKeeper(CONNECTION_STRING, SESSION_TIMEOUT, this); 18 | } 19 | 20 | @Override 21 | public void process(WatchedEvent event) { 22 | if(event.getState() == Event.KeeperState.SyncConnected){ 23 | registSelf(); 24 | } 25 | } 26 | 27 | private void registSelf(){ 28 | try { 29 | zk.create(SERVICE_NAME, "service two".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL); 30 | } catch (KeeperException e) { 31 | e.printStackTrace(); 32 | } catch (InterruptedException e) { 33 | e.printStackTrace(); 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /netty-example/src/test/java/com/github/loafer/channelhandler/ThirdChannelHandler.java: -------------------------------------------------------------------------------- 1 | package com.github.loafer.channelhandler; 2 | 3 | import io.netty.buffer.ByteBuf; 4 | import io.netty.buffer.ByteBufUtil; 5 | import io.netty.buffer.Unpooled; 6 | import io.netty.channel.ChannelFutureListener; 7 | import io.netty.channel.ChannelHandlerContext; 8 | import io.netty.channel.SimpleChannelInboundHandler; 9 | import io.netty.util.ReferenceCountUtil; 10 | 11 | /** 12 | * @author zhaojh. 13 | */ 14 | public class ThirdChannelHandler extends SimpleChannelInboundHandler { 15 | 16 | @Override 17 | protected void channelRead0(ChannelHandlerContext ctx, 18 | ByteBuf msg) throws Exception { 19 | System.out.println("ThirdChannelHandler received: " + ByteBufUtil.hexDump(msg.readBytes(msg.readableBytes()))); 20 | } 21 | 22 | @Override 23 | public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { 24 | // super.channelReadComplete(ctx); 25 | System.out.println("ThirdChannelHandler read complete."); 26 | ctx.writeAndFlush(Unpooled.EMPTY_BUFFER) 27 | .addListener(ChannelFutureListener.CLOSE); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /netty-example/src/main/java/com/github/loafer/timer/TimerClinetHandler.java: -------------------------------------------------------------------------------- 1 | package com.github.loafer.timer; 2 | 3 | import io.netty.buffer.ByteBuf; 4 | import io.netty.channel.ChannelHandlerContext; 5 | import io.netty.channel.ChannelInboundHandlerAdapter; 6 | import io.netty.util.ReferenceCountUtil; 7 | 8 | import java.util.Date; 9 | 10 | /** 11 | * @author zhaojh. 12 | */ 13 | public class TimerClinetHandler extends ChannelInboundHandlerAdapter { 14 | @Override 15 | public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { 16 | // ByteBuf m = (ByteBuf) msg; 17 | // try { 18 | // long currentTimeMillis = (m.readUnsignedInt() - 2208988800L) * 1000L; 19 | // System.out.println(new Date(currentTimeMillis)); 20 | // ctx.close(); 21 | // }finally { 22 | // m.release(); 23 | // } 24 | 25 | 26 | try{ 27 | UnixTime m = (UnixTime) msg; 28 | System.out.println(m); 29 | ctx.close(); 30 | }finally { 31 | ReferenceCountUtil.release(msg); 32 | } 33 | } 34 | 35 | @Override 36 | public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { 37 | cause.printStackTrace(); 38 | ctx.close(); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /netty-example/src/main/java/com/github/loafer/timer/TimerServerHandler.java: -------------------------------------------------------------------------------- 1 | package com.github.loafer.timer; 2 | 3 | import io.netty.buffer.ByteBuf; 4 | import io.netty.channel.ChannelFuture; 5 | import io.netty.channel.ChannelFutureListener; 6 | import io.netty.channel.ChannelHandlerContext; 7 | import io.netty.channel.ChannelInboundHandlerAdapter; 8 | 9 | /** 10 | * @author zhaojh. 11 | */ 12 | public class TimerServerHandler extends ChannelInboundHandlerAdapter{ 13 | @Override 14 | public void channelActive(final ChannelHandlerContext ctx) throws Exception { 15 | // ByteBuf time = ctx.alloc().buffer(4); 16 | // time.writeInt((int) (System.currentTimeMillis()/1000L + 2208988800L)); 17 | // 18 | // final ChannelFuture f = ctx.writeAndFlush(time); 19 | // //关闭通道 20 | // f.addListener(new ChannelFutureListener() { 21 | // @Override 22 | // public void operationComplete(ChannelFuture future) throws Exception { 23 | // if(f == future){ 24 | // ctx.close(); 25 | // } 26 | // } 27 | // }); 28 | 29 | 30 | ChannelFuture f = ctx.writeAndFlush(new UnixTime()); 31 | f.addListener(ChannelFutureListener.CLOSE); 32 | 33 | } 34 | 35 | @Override 36 | public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { 37 | cause.printStackTrace(); 38 | ctx.close(); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /zookeeper-offical-client/src/test/java/com/github/loafer/EphemeralNodeTest.java: -------------------------------------------------------------------------------- 1 | package com.github.loafer; 2 | 3 | import org.apache.zookeeper.*; 4 | 5 | import java.io.IOException; 6 | import java.util.Scanner; 7 | 8 | /** 9 | * @author zhaojh. 10 | */ 11 | public class EphemeralNodeTest { 12 | private static final String CONNECTION_STRING = "192.168.56.120:2181"; 13 | private static final int CONNECTION_TIMEOUT = 3000; 14 | 15 | public static void main(String[] args) throws IOException, InterruptedException, KeeperException { 16 | ZooKeeper zk = new ZooKeeper(CONNECTION_STRING, CONNECTION_TIMEOUT, new Watcher() { 17 | @Override 18 | public void process(WatchedEvent event) { 19 | System.out.println("state: " + event.getState()); 20 | String message = String.format("在节点[%s]上触发事件[%s]", event.getPath(), event.getType()); 21 | System.out.println(message); 22 | } 23 | }); 24 | 25 | zk.create("/quick4j", "quick4j".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL); 26 | 27 | 28 | 29 | Scanner scanner = new Scanner(System.in); 30 | System.out.println("请输入'quit'结束程序:"); 31 | while (true){ 32 | String commond = scanner.nextLine(); 33 | if(commond.equalsIgnoreCase("quit")){ 34 | System.out.println("bye!"); 35 | break; 36 | } 37 | System.out.println(">>" + commond); 38 | } 39 | 40 | zk.close(); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /netty-example/src/main/java/com/github/loafer/echo/EchoClientHandler.java: -------------------------------------------------------------------------------- 1 | package com.github.loafer.echo; 2 | 3 | import io.netty.buffer.ByteBuf; 4 | import io.netty.buffer.Unpooled; 5 | import io.netty.channel.ChannelFutureListener; 6 | import io.netty.channel.ChannelHandlerContext; 7 | import io.netty.channel.ChannelInboundHandlerAdapter; 8 | import io.netty.util.CharsetUtil; 9 | import io.netty.util.ReferenceCountUtil; 10 | 11 | /** 12 | * @author zhaojh. 13 | */ 14 | public class EchoClientHandler extends ChannelInboundHandlerAdapter { 15 | private final String message = "Hello Netty!"; 16 | 17 | @Override 18 | public void channelActive(ChannelHandlerContext ctx) throws Exception { 19 | ctx.writeAndFlush(Unpooled.copiedBuffer(message, CharsetUtil.UTF_8)); 20 | } 21 | 22 | @Override 23 | public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { 24 | try { 25 | ByteBuf in = (ByteBuf) msg; 26 | System.out.println("Received from Server: " + in.toString(CharsetUtil.US_ASCII)); 27 | ctx.close(); 28 | }finally { 29 | ReferenceCountUtil.release(msg); 30 | } 31 | } 32 | 33 | // @Override 34 | // public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { 35 | // ctx.write(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE); 36 | // } 37 | 38 | @Override 39 | public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { 40 | cause.printStackTrace(); 41 | ctx.close(); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /netty-example/src/main/java/com/github/loafer/sample/SimpleChannelHandler.java: -------------------------------------------------------------------------------- 1 | package com.github.loafer.sample; 2 | 3 | import io.netty.buffer.ByteBuf; 4 | import io.netty.buffer.Unpooled; 5 | import io.netty.channel.ChannelFutureListener; 6 | import io.netty.channel.ChannelHandlerContext; 7 | import io.netty.channel.SimpleChannelInboundHandler; 8 | 9 | /** 10 | * @author zhaojh. 11 | */ 12 | public class SimpleChannelHandler extends SimpleChannelInboundHandler { 13 | @Override 14 | protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception { 15 | System.out.println("Channel received: " + msg); 16 | } 17 | 18 | @Override 19 | public void channelRegistered(ChannelHandlerContext ctx) throws Exception { 20 | System.out.println("Channel is registered. " + ctx.channel()); 21 | super.channelRegistered(ctx); 22 | } 23 | 24 | @Override 25 | public void channelActive(ChannelHandlerContext ctx) throws Exception { 26 | System.out.println("Channel is connected. " + ctx.channel()); 27 | super.channelActive(ctx); 28 | } 29 | 30 | @Override 31 | public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { 32 | System.out.println("Message read complete."); 33 | super.channelReadComplete(ctx); 34 | ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE); 35 | } 36 | 37 | @Override 38 | public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { 39 | super.exceptionCaught(ctx, cause); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /zookeeper-offical-client/src/test/java/com/github/loafer/ServiceDiscovery.java: -------------------------------------------------------------------------------- 1 | package com.github.loafer; 2 | 3 | import static com.github.loafer.zookeeper.service.Constant.*; 4 | import org.apache.zookeeper.KeeperException; 5 | import org.apache.zookeeper.WatchedEvent; 6 | import org.apache.zookeeper.Watcher; 7 | import org.apache.zookeeper.ZooKeeper; 8 | 9 | import java.io.IOException; 10 | import java.util.List; 11 | 12 | /** 13 | * @author zhaojh. 14 | */ 15 | public class ServiceDiscovery implements Watcher{ 16 | private ZooKeeper zooKeeper; 17 | private boolean monitoring; 18 | 19 | public ServiceDiscovery() throws IOException { 20 | zooKeeper = new ZooKeeper(CONNECTION_STRING, SESSION_TIMEOUT, this); 21 | } 22 | 23 | @Override 24 | public void process(WatchedEvent event) { 25 | if(event.getState() == Event.KeeperState.SyncConnected && ! monitoring){ 26 | watchServiceZnode(); 27 | monitoring = true; 28 | } 29 | 30 | if(event.getType() == Event.EventType.NodeChildrenChanged){ 31 | watchServiceZnode(); 32 | System.out.println(1); 33 | } 34 | } 35 | 36 | private void watchServiceZnode(){ 37 | try { 38 | List serviceList = zooKeeper.getChildren("/", this); 39 | for (String service : serviceList){ 40 | System.out.println(service); 41 | } 42 | System.out.println("================"); 43 | } catch (KeeperException e) { 44 | e.printStackTrace(); 45 | } catch (InterruptedException e) { 46 | e.printStackTrace(); 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /zookeeper-offical-client/src/test/java/com/github/loafer/ExampleTest.java: -------------------------------------------------------------------------------- 1 | package com.github.loafer; 2 | 3 | import org.apache.zookeeper.*; 4 | import org.junit.Before; 5 | import org.junit.Test; 6 | 7 | import java.io.IOException; 8 | import java.util.concurrent.CountDownLatch; 9 | 10 | /** 11 | * @author zhaojh. 12 | */ 13 | public class ExampleTest { 14 | private CountDownLatch downLatch = new CountDownLatch(1); 15 | private ZooKeeper zk; 16 | private Watcher watcher = new Watcher() { 17 | @Override 18 | public void process(WatchedEvent event) { 19 | System.out.println(event.toString()); 20 | if(event.getState() == Event.KeeperState.SyncConnected){ 21 | downLatch.countDown(); 22 | } 23 | } 24 | }; 25 | 26 | @Before 27 | public void setup() throws IOException, InterruptedException { 28 | zk = new ZooKeeper("192.168.56.120:2181", 5000, watcher); 29 | downLatch.await(); 30 | } 31 | 32 | // @Test 33 | public void testExists() throws KeeperException, InterruptedException, IOException { 34 | zk.exists("/loafer", true); 35 | zk.close(); 36 | 37 | } 38 | 39 | // @Test 40 | public void testEphemeral() throws KeeperException, InterruptedException, IOException { 41 | zk.create("/quick4j", null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); 42 | zk.create("/quick4j/helloService", null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL); 43 | zk.create("/quick4j/helloService/providers", null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL); 44 | 45 | System.in.read(); 46 | zk.close(); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /netty-example/src/main/java/com/github/loafer/sample/SampleNettyServer.java: -------------------------------------------------------------------------------- 1 | package com.github.loafer.sample; 2 | 3 | import io.netty.bootstrap.ServerBootstrap; 4 | import io.netty.channel.Channel; 5 | import io.netty.channel.ChannelFuture; 6 | import io.netty.channel.ChannelInitializer; 7 | import io.netty.channel.EventLoopGroup; 8 | import io.netty.channel.nio.NioEventLoopGroup; 9 | import io.netty.channel.socket.nio.NioServerSocketChannel; 10 | 11 | /** 12 | * @author zhaojh. 13 | */ 14 | public class SampleNettyServer { 15 | private final int port; 16 | 17 | public SampleNettyServer(int port) { 18 | this.port = port; 19 | } 20 | 21 | public void start() throws InterruptedException { 22 | EventLoopGroup group = new NioEventLoopGroup(); 23 | try { 24 | ServerBootstrap b = new ServerBootstrap(); 25 | b.group(group) 26 | .channel(NioServerSocketChannel.class) 27 | .localAddress(port) 28 | .childHandler(new ChannelInitializer() { 29 | @Override 30 | protected void initChannel(Channel ch) throws Exception { 31 | ch.pipeline().addLast(new SimpleChannelHandler()); 32 | } 33 | }); 34 | 35 | ChannelFuture f = b.bind().sync(); 36 | System.out.println("SampleNetty Server is started at:" + port); 37 | f.channel().closeFuture().sync(); 38 | }finally { 39 | group.shutdownGracefully().sync(); 40 | } 41 | } 42 | 43 | public static void main(String[] args) throws InterruptedException { 44 | new SampleNettyServer(8888).start(); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /netty-example/src/main/java/com/github/loafer/discard/DiscardServer.java: -------------------------------------------------------------------------------- 1 | package com.github.loafer.discard; 2 | 3 | import io.netty.bootstrap.ServerBootstrap; 4 | import io.netty.channel.*; 5 | import io.netty.channel.nio.NioEventLoopGroup; 6 | import io.netty.channel.socket.nio.NioServerSocketChannel; 7 | 8 | /** 9 | * @author zhaojh. 10 | */ 11 | public class DiscardServer { 12 | private final int port; 13 | 14 | public DiscardServer(int port) { 15 | this.port = port; 16 | } 17 | 18 | public void start() throws InterruptedException { 19 | EventLoopGroup bossGroup = new NioEventLoopGroup(); 20 | EventLoopGroup workerGroup = new NioEventLoopGroup(); 21 | try{ 22 | ServerBootstrap b = new ServerBootstrap(); 23 | b.group(bossGroup, workerGroup) 24 | .channel(NioServerSocketChannel.class) 25 | .localAddress(port) 26 | .childHandler(new ChannelInitializer() { 27 | @Override 28 | protected void initChannel(Channel ch) throws Exception { 29 | ch.pipeline().addLast(new DiscardServerHandler()); 30 | } 31 | }) 32 | .option(ChannelOption.SO_BACKLOG, 128) 33 | .childOption(ChannelOption.SO_KEEPALIVE, true); 34 | 35 | ChannelFuture f = b.bind().sync(); 36 | f.channel().closeFuture().sync(); 37 | }finally { 38 | workerGroup.shutdownGracefully(); 39 | bossGroup.shutdownGracefully(); 40 | } 41 | } 42 | 43 | public static void main(String[] args) throws InterruptedException { 44 | new DiscardServer(8888).start(); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /netty-example/src/main/java/com/github/loafer/echo/EchoServer.java: -------------------------------------------------------------------------------- 1 | package com.github.loafer.echo; 2 | 3 | import io.netty.bootstrap.ServerBootstrap; 4 | import io.netty.channel.Channel; 5 | import io.netty.channel.ChannelFuture; 6 | import io.netty.channel.ChannelInitializer; 7 | import io.netty.channel.EventLoopGroup; 8 | import io.netty.channel.nio.NioEventLoopGroup; 9 | import io.netty.channel.socket.nio.NioServerSocketChannel; 10 | 11 | /** 12 | * @author zhaojh. 13 | */ 14 | public class EchoServer { 15 | private final int port; 16 | 17 | public EchoServer(int port) { 18 | this.port = port; 19 | } 20 | 21 | public void start() throws InterruptedException { 22 | EventLoopGroup bossGroup = new NioEventLoopGroup(); 23 | EventLoopGroup workersGroup = new NioEventLoopGroup(); 24 | try{ 25 | ServerBootstrap b = new ServerBootstrap(); 26 | b.group(bossGroup, workersGroup) 27 | .channel(NioServerSocketChannel.class) 28 | .childHandler(new ChannelInitializer() { 29 | @Override 30 | protected void initChannel(Channel ch) throws Exception { 31 | ch.pipeline().addLast(new EchoServerHandler()); 32 | } 33 | }); 34 | 35 | ChannelFuture f = b.bind(port).sync(); 36 | System.out.println("Echo Server started and listen on: " + port); 37 | f.channel().closeFuture().sync(); 38 | }finally { 39 | workersGroup.shutdownGracefully(); 40 | bossGroup.shutdownGracefully(); 41 | } 42 | } 43 | 44 | public static void main(String[] args) throws InterruptedException { 45 | new EchoServer(8888).start(); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /master-worker-example/src/main/java/com/github/loafer/zookeeper/example/Client.java: -------------------------------------------------------------------------------- 1 | package com.github.loafer.zookeeper.example; 2 | 3 | import org.apache.zookeeper.*; 4 | import org.apache.zookeeper.KeeperException.Code; 5 | import org.apache.zookeeper.AsyncCallback.StringCallback; 6 | import org.apache.zookeeper.ZooDefs.Ids; 7 | import org.slf4j.Logger; 8 | import org.slf4j.LoggerFactory; 9 | 10 | import java.io.IOException; 11 | 12 | /** 13 | * @author zhaojh. 14 | */ 15 | public class Client implements Watcher { 16 | private static Logger logger = LoggerFactory.getLogger(Client.class); 17 | private ZooKeeper zk; 18 | private String hostport; 19 | 20 | public Client(String hostport) { 21 | this.hostport = hostport; 22 | } 23 | 24 | @Override 25 | public void process(WatchedEvent event) { 26 | 27 | } 28 | 29 | public void startZK() throws IOException { 30 | zk = new ZooKeeper(hostport, 2000, this); 31 | } 32 | 33 | public void stopZK() throws InterruptedException { 34 | zk.close(); 35 | } 36 | 37 | public void queueCommand(String command){ 38 | zk.create( 39 | "/task-", 40 | command.getBytes(), 41 | Ids.OPEN_ACL_UNSAFE, 42 | CreateMode.PERSISTENT_SEQUENTIAL, 43 | createTaskCallback, 44 | command 45 | ); 46 | } 47 | 48 | private StringCallback createTaskCallback = new StringCallback() { 49 | @Override 50 | public void processResult(int rc, String path, Object ctx, String name) { 51 | switch (Code.get(rc)){ 52 | case OK: 53 | logger.info("===>{} created. To deal with the [{}]", name, ctx.toString()); 54 | break; 55 | } 56 | } 57 | }; 58 | } 59 | -------------------------------------------------------------------------------- /netty-example/src/main/java/com/github/loafer/timer/TimerClient.java: -------------------------------------------------------------------------------- 1 | package com.github.loafer.timer; 2 | 3 | import io.netty.bootstrap.Bootstrap; 4 | import io.netty.channel.ChannelFuture; 5 | import io.netty.channel.ChannelInitializer; 6 | import io.netty.channel.ChannelOption; 7 | import io.netty.channel.EventLoopGroup; 8 | import io.netty.channel.nio.NioEventLoopGroup; 9 | import io.netty.channel.socket.SocketChannel; 10 | import io.netty.channel.socket.nio.NioSocketChannel; 11 | 12 | /** 13 | * @author zhaojh. 14 | */ 15 | public class TimerClient { 16 | private final String host; 17 | private final int port; 18 | 19 | public TimerClient(String host, int port) { 20 | this.host = host; 21 | this.port = port; 22 | } 23 | 24 | public void start() throws InterruptedException { 25 | EventLoopGroup workerGroup = new NioEventLoopGroup(); 26 | try{ 27 | Bootstrap b = new Bootstrap(); 28 | b.group(workerGroup) 29 | .channel(NioSocketChannel.class) 30 | .option(ChannelOption.SO_KEEPALIVE, true) 31 | .handler(new ChannelInitializer() { 32 | @Override 33 | protected void initChannel(SocketChannel ch) throws Exception { 34 | ch.pipeline() 35 | .addLast(new TimerDecoder()) 36 | .addLast(new TimerClinetHandler()); 37 | } 38 | }); 39 | 40 | ChannelFuture f = b.connect(host, port).sync(); 41 | f.channel().closeFuture().sync(); 42 | }finally { 43 | workerGroup.shutdownGracefully(); 44 | } 45 | 46 | } 47 | 48 | public static void main(String[] args) throws InterruptedException { 49 | new TimerClient("localhost", 8888).start(); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /netty-example/src/main/java/com/github/loafer/timer/TimerServer.java: -------------------------------------------------------------------------------- 1 | package com.github.loafer.timer; 2 | 3 | import io.netty.bootstrap.ServerBootstrap; 4 | import io.netty.channel.Channel; 5 | import io.netty.channel.ChannelFuture; 6 | import io.netty.channel.ChannelInitializer; 7 | import io.netty.channel.EventLoopGroup; 8 | import io.netty.channel.nio.NioEventLoopGroup; 9 | import io.netty.channel.socket.nio.NioServerSocketChannel; 10 | 11 | /** 12 | * @author zhaojh. 13 | */ 14 | public class TimerServer { 15 | private final int port; 16 | 17 | public TimerServer(int port) { 18 | this.port = port; 19 | } 20 | 21 | public void start() throws InterruptedException { 22 | EventLoopGroup bossGroup = new NioEventLoopGroup(); 23 | EventLoopGroup workerGroup = new NioEventLoopGroup(); 24 | 25 | try{ 26 | ServerBootstrap b = new ServerBootstrap(); 27 | b.group(bossGroup, workerGroup) 28 | .channel(NioServerSocketChannel.class) 29 | .childHandler(new ChannelInitializer() { 30 | @Override 31 | protected void initChannel(Channel ch) throws Exception { 32 | ch.pipeline() 33 | .addLast(new TimerEncoder()) 34 | .addLast(new TimerServerHandler()); 35 | } 36 | }); 37 | 38 | ChannelFuture f = b.bind(port).sync(); 39 | System.out.println("Time Server started and listen on: " + port); 40 | f.channel().closeFuture().sync(); 41 | }finally { 42 | workerGroup.shutdownGracefully(); 43 | bossGroup.shutdownGracefully(); 44 | } 45 | } 46 | 47 | public static void main(String[] args) throws InterruptedException { 48 | new TimerServer(8888).start(); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /netty-example/src/test/java/com/github/loafer/channelhandler/EchoServer.java: -------------------------------------------------------------------------------- 1 | package com.github.loafer.channelhandler; 2 | 3 | import io.netty.bootstrap.ServerBootstrap; 4 | import io.netty.channel.Channel; 5 | import io.netty.channel.ChannelFuture; 6 | import io.netty.channel.ChannelInitializer; 7 | import io.netty.channel.EventLoopGroup; 8 | import io.netty.channel.nio.NioEventLoopGroup; 9 | import io.netty.channel.socket.nio.NioServerSocketChannel; 10 | 11 | /** 12 | * @author zhaojh. 13 | */ 14 | public class EchoServer { 15 | private final int port; 16 | 17 | public EchoServer(int port) { 18 | this.port = port; 19 | } 20 | 21 | public void start() throws InterruptedException { 22 | EventLoopGroup group = new NioEventLoopGroup(); 23 | try{ 24 | ServerBootstrap b = new ServerBootstrap(); 25 | b.group(group) 26 | .channel(NioServerSocketChannel.class) 27 | .localAddress(port) 28 | .childHandler(new ChannelInitializer() { 29 | @Override 30 | protected void initChannel(Channel channel) throws Exception { 31 | channel.pipeline() 32 | .addLast("1", new FirstChannelHandler()) 33 | .addLast("2", new SecondChannelHandler()) 34 | .addLast("3", new ThirdChannelHandler()); 35 | } 36 | }); 37 | 38 | ChannelFuture f = b.bind().sync(); 39 | System.out.println("EchoServer started and listen on: " + port); 40 | f.channel().closeFuture().sync(); 41 | }finally { 42 | group.shutdownGracefully().sync(); 43 | } 44 | } 45 | 46 | public static void main(String[] args) throws InterruptedException { 47 | new EchoServer(9999).start(); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /zookeeper-offical-client/src/test/java/com/github/loafer/WatchZnodeTest.java: -------------------------------------------------------------------------------- 1 | package com.github.loafer; 2 | 3 | import org.apache.zookeeper.*; 4 | 5 | import java.io.IOException; 6 | import java.util.Scanner; 7 | 8 | /** 9 | * @author zhaojh. 10 | */ 11 | public class WatchZnodeTest { 12 | private static final String CONNECTION_STRING = "192.168.56.120:2181"; 13 | private static final int CONNECTION_TIMEOUT = 3000; 14 | private static final String ZK_SERVICE_REGISTRY_PATH = "/serviceRegistry"; 15 | 16 | private static void watchServiceRegistryZnode(final ZooKeeper zk){ 17 | try { 18 | zk.exists(ZK_SERVICE_REGISTRY_PATH, new Watcher() { 19 | @Override 20 | public void process(WatchedEvent event) { 21 | String message = String.format("在节点[%s]上触发事件[%s]", event.getPath(), event.getType()); 22 | System.out.println(message); 23 | 24 | watchServiceRegistryZnode(zk); 25 | } 26 | }); 27 | } catch (KeeperException e) { 28 | e.printStackTrace(); 29 | } catch (InterruptedException e) { 30 | e.printStackTrace(); 31 | } 32 | } 33 | 34 | 35 | public static void main(String[] args) throws IOException, KeeperException, InterruptedException { 36 | 37 | final ZooKeeper zk = new ZooKeeper(CONNECTION_STRING, CONNECTION_TIMEOUT, null); 38 | 39 | zk.create(ZK_SERVICE_REGISTRY_PATH, "serviceRegistry".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); 40 | 41 | watchServiceRegistryZnode(zk); 42 | 43 | Scanner scanner = new Scanner(System.in); 44 | System.out.println("请输入'quit'结束程序:"); 45 | while (true){ 46 | String commond = scanner.nextLine(); 47 | if(commond.equalsIgnoreCase("quit")){ 48 | System.out.println("bye!"); 49 | break; 50 | } 51 | System.out.println(">>" + commond); 52 | } 53 | 54 | zk.close(); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /netty-example/src/main/java/com/github/loafer/echo/EchoClient.java: -------------------------------------------------------------------------------- 1 | package com.github.loafer.echo; 2 | 3 | import io.netty.bootstrap.Bootstrap; 4 | import io.netty.channel.*; 5 | import io.netty.channel.nio.NioEventLoopGroup; 6 | import io.netty.channel.socket.SocketChannel; 7 | import io.netty.channel.socket.nio.NioSocketChannel; 8 | 9 | import java.net.InetAddress; 10 | 11 | 12 | /** 13 | * @author zhaojh. 14 | */ 15 | public class EchoClient { 16 | private final String host; 17 | private final int port; 18 | 19 | public EchoClient(String host, int port) { 20 | this.host = host; 21 | this.port = port; 22 | } 23 | 24 | public void start() throws InterruptedException { 25 | EventLoopGroup group = new NioEventLoopGroup(); 26 | 27 | try{ 28 | Bootstrap b = new Bootstrap(); 29 | b.group(group) 30 | .channel(NioSocketChannel.class) 31 | // .option(ChannelOption.TCP_NODELAY, true) 32 | .handler(new ChannelInitializer() { 33 | @Override 34 | protected void initChannel(SocketChannel ch) throws Exception { 35 | ch.pipeline().addLast(new EchoClientHandler()); 36 | } 37 | }); 38 | 39 | 40 | ChannelFuture f = b.connect(host, port).sync(); 41 | f.addListener(new ChannelFutureListener() { 42 | @Override 43 | public void operationComplete(ChannelFuture future) throws Exception { 44 | if(future.isSuccess()){ 45 | System.out.println("Connection established."); 46 | }else{ 47 | System.out.println("Connection attempt failed."); 48 | } 49 | } 50 | }); 51 | 52 | f.channel().closeFuture().sync(); 53 | }finally { 54 | group.shutdownGracefully(); 55 | } 56 | } 57 | 58 | public static void main(String[] args) throws InterruptedException { 59 | new EchoClient("localhost", 8888).start(); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /netty-example/pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | 5 | com.github.loafer 6 | netty-example 7 | 1.0-SNAPSHOT 8 | jar 9 | 10 | netty-example 11 | http://maven.apache.org 12 | 13 | 14 | UTF-8 15 | 16 | 17 | 18 | 19 | org.slf4j 20 | slf4j-simple 21 | 1.7.5 22 | 23 | 24 | 25 | io.netty 26 | netty-all 27 | 4.0.25.Final 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | junit 45 | junit 46 | 4.11 47 | test 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | -------------------------------------------------------------------------------- /zookeeper-offical-client/src/test/java/com/github/loafer/BasicOperationForClient.java: -------------------------------------------------------------------------------- 1 | package com.github.loafer; 2 | 3 | import org.apache.zookeeper.*; 4 | 5 | import java.io.IOException; 6 | 7 | /** 8 | * @author zhaojh. 9 | */ 10 | public class BasicOperationForClient { 11 | private static final String CONNECTSTRING = "192.168.56.120:2181"; 12 | private static final int CONNECTION_TIMEOUT = 3000; 13 | 14 | public static void main(String[] args) throws IOException, KeeperException, InterruptedException { 15 | ZooKeeper zk = new ZooKeeper(CONNECTSTRING, CONNECTION_TIMEOUT, new Watcher() { 16 | @Override 17 | public void process(WatchedEvent event) { 18 | String message = String.format("已经触发了[%s]事件。节点:[%s]", event.getType(), event.getWrapper().getPath()); 19 | System.out.println(message); 20 | } 21 | }); 22 | 23 | zk.create("/quick4j", "quick4j".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); 24 | //取"/quick4j"节点 25 | System.out.println("节点[/quick4j]数据: " + new String(zk.getData("/quick4j", true, null))); 26 | 27 | 28 | zk.create("/quick4j/upm", "upm".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); 29 | //取"/quick4j"子节点 30 | System.out.println("节点[/quick4j]子节点: " + zk.getChildren("/quick4j", true)); 31 | System.out.println("节点[/quick4j/upm]数据:" + new String(zk.getData("/quick4j/upm", true, null))); 32 | 33 | 34 | //修改"/quick4j/upm"节点 35 | zk.setData("/quick4j/upm", "quick4j-upm".getBytes(), -1); 36 | //获取"/quick4j"节点状态 37 | System.out.println("节点[/quick4j/upm]状态:[" + zk.exists("/quick4j/upm", true) + "]"); 38 | 39 | //创建"/quick4j"的另一个子节点"dws" 40 | zk.create("/quick4j/dws", "quick4j-dws".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); 41 | //获取"/quick4j/quick4j-dws"节点数据 42 | System.out.println("节点[/quick4j/dws]数据: " + new String(zk.getData("/quick4j/dws", true, null))); 43 | 44 | //取"/quick4j"子节点 45 | System.out.println("节点[/quick4j]子节点: " + zk.getChildren("/quick4j", true)); 46 | 47 | //删除子节点 48 | zk.delete("/quick4j/upm", -1); 49 | zk.delete("/quick4j/dws", -1); 50 | 51 | 52 | //删除父节点 53 | zk.delete("/quick4j", -1); 54 | zk.close(); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /master-worker-example/pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | 5 | com.github.loafer 6 | master-worker-example 7 | 1.0-SNAPSHOT 8 | jar 9 | 10 | master-worker-example 11 | http://maven.apache.org 12 | 13 | 14 | UTF-8 15 | 16 | 17 | 18 | 19 | org.apache.zookeeper 20 | zookeeper 21 | 3.4.6 22 | 23 | 24 | org.slf4j 25 | slf4j-log4j12 26 | 27 | 28 | log4j 29 | log4j 30 | 31 | 32 | 33 | 34 | 35 | org.slf4j 36 | slf4j-api 37 | 1.7.5 38 | 39 | 40 | org.slf4j 41 | slf4j-simple 42 | 1.7.5 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | junit 57 | junit 58 | 4.11 59 | test 60 | 61 | 62 | 63 | -------------------------------------------------------------------------------- /zookeeper-client-example/pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | 5 | com.github.loafer 6 | zookeeper-client-example 7 | 1.0-SNAPSHOT 8 | jar 9 | 10 | zookeeper-client-example 11 | http://maven.apache.org 12 | 13 | 14 | UTF-8 15 | 16 | 17 | 18 | 19 | org.apache.curator 20 | curator-framework 21 | 2.7.1 22 | 23 | 24 | 25 | org.apache.zookeeper 26 | zookeeper 27 | 3.4.6 28 | 29 | 30 | org.slf4j 31 | slf4j-log4j12 32 | 33 | 34 | log4j 35 | log4j 36 | 37 | 38 | 39 | 40 | 41 | org.springframework 42 | spring-context 43 | 4.0.7.RELEASE 44 | 45 | 46 | 47 | com.fasterxml.jackson.core 48 | jackson-databind 49 | 2.3.3 50 | 51 | 52 | 53 | org.slf4j 54 | slf4j-simple 55 | 1.7.5 56 | 57 | 58 | 59 | org.springframework 60 | spring-test 61 | 4.0.7.RELEASE 62 | test 63 | 64 | 65 | 66 | junit 67 | junit 68 | 4.11 69 | test 70 | 71 | 72 | 73 | -------------------------------------------------------------------------------- /master-worker-example/src/main/java/com/github/loafer/zookeeper/example/Worker.java: -------------------------------------------------------------------------------- 1 | package com.github.loafer.zookeeper.example; 2 | 3 | import org.apache.zookeeper.*; 4 | import org.apache.zookeeper.AsyncCallback.StringCallback; 5 | import org.apache.zookeeper.AsyncCallback.Children2Callback; 6 | import org.apache.zookeeper.KeeperException.Code; 7 | import org.apache.zookeeper.data.Stat; 8 | import org.slf4j.Logger; 9 | import org.slf4j.LoggerFactory; 10 | 11 | import java.io.IOException; 12 | import java.util.List; 13 | 14 | /** 15 | * @author zhaojh. 16 | */ 17 | public class Worker implements Watcher, Runnable { 18 | private static Logger logger = LoggerFactory.getLogger(Worker.class); 19 | private ZooKeeper zk; 20 | private String hostport; 21 | 22 | public Worker(String hostport) { 23 | this.hostport = hostport; 24 | } 25 | 26 | @Override 27 | public void process(WatchedEvent event) { 28 | System.out.println(event.toString()); 29 | } 30 | 31 | @Override 32 | public void run() { 33 | try { 34 | startZK(); 35 | register(); 36 | System.in.read(); 37 | stopZK(); 38 | } catch (IOException e) { 39 | e.printStackTrace(); 40 | } catch (InterruptedException e) { 41 | e.printStackTrace(); 42 | } 43 | } 44 | 45 | public void startZK() throws IOException { 46 | zk = new ZooKeeper(hostport, 2000, this); 47 | } 48 | 49 | public void stopZK() throws InterruptedException { 50 | zk.close(); 51 | } 52 | 53 | public void register(){ 54 | zk.create( 55 | "/worker-", 56 | "Idle".getBytes(), 57 | ZooDefs.Ids.OPEN_ACL_UNSAFE, 58 | CreateMode.EPHEMERAL_SEQUENTIAL, 59 | createWorkerCallback, 60 | null 61 | ); 62 | } 63 | 64 | private StringCallback createWorkerCallback = new StringCallback() { 65 | @Override 66 | public void processResult(int rc, String path, Object ctx, String name) { 67 | switch (Code.get(rc)){ 68 | case CONNECTIONLOSS: 69 | register(); 70 | break; 71 | case OK: 72 | logger.info("===>[Worker]{} created.", name); 73 | break; 74 | case NODEEXISTS: 75 | logger.info("===>[Worker]{} already registered.", name); 76 | break; 77 | default: 78 | logger.info("===>[Worker]Something went wrong."); 79 | break; 80 | } 81 | } 82 | }; 83 | } 84 | -------------------------------------------------------------------------------- /zookeeper-client-example/src/main/java/com/github/loafer/rpc/ServiceDiscovery.java: -------------------------------------------------------------------------------- 1 | package com.github.loafer.rpc; 2 | 3 | import com.github.loafer.rpc.annotation.ServiceProvider; 4 | import com.github.loafer.rpc.annotation.ServiceProviders; 5 | import org.slf4j.Logger; 6 | import org.slf4j.LoggerFactory; 7 | import org.springframework.beans.BeansException; 8 | import org.springframework.beans.factory.DisposableBean; 9 | import org.springframework.beans.factory.InitializingBean; 10 | import org.springframework.beans.factory.config.BeanPostProcessor; 11 | 12 | import javax.annotation.Resource; 13 | import java.util.HashMap; 14 | import java.util.Map; 15 | 16 | /** 17 | * @author zhaojh. 18 | */ 19 | public class ServiceDiscovery implements InitializingBean, BeanPostProcessor, DisposableBean { 20 | private static final Logger logger = LoggerFactory.getLogger(ServiceDiscovery.class); 21 | 22 | private Map providerMap = new HashMap(); 23 | private ServiceRegistry serviceRegistry; 24 | 25 | public void setServiceRegistry(ServiceRegistry serviceRegistry) { 26 | this.serviceRegistry = serviceRegistry; 27 | } 28 | 29 | @Override 30 | public void afterPropertiesSet() throws Exception { 31 | bootstrap(); 32 | } 33 | 34 | @Override 35 | public Object postProcessBeforeInitialization(Object bean, String beanName) 36 | throws BeansException { 37 | return bean; 38 | } 39 | 40 | @Override 41 | public Object postProcessAfterInitialization(Object bean, String beanName) 42 | throws BeansException { 43 | if(bean.getClass().isAnnotationPresent(ServiceProviders.class)){ 44 | ServiceProviders serviceProviders = bean.getClass().getAnnotation(ServiceProviders.class); 45 | ServiceProvider[] providers = serviceProviders.value(); 46 | for (ServiceProvider provider : providers){ 47 | ServiceInstance serviceInstance = buildServiceInstance(provider, bean); 48 | registerService(serviceInstance); 49 | } 50 | } 51 | 52 | if(bean.getClass().isAnnotationPresent(ServiceProvider.class)){ 53 | ServiceProvider provider = bean.getClass().getAnnotation(ServiceProvider.class); 54 | ServiceInstance serviceInstance = buildServiceInstance(provider, bean); 55 | registerService(serviceInstance); 56 | } 57 | 58 | return bean; 59 | } 60 | 61 | @Override 62 | public void destroy() throws Exception { 63 | } 64 | 65 | private void bootstrap() throws Exception { 66 | 67 | } 68 | 69 | private void registerService(ServiceInstance serviceInstance) throws ServiceRegisterException{ 70 | if(providerMap.containsKey(serviceInstance.getName())){ 71 | return; 72 | } 73 | 74 | logger.info("register [{}]", serviceInstance.getName()); 75 | providerMap.put(serviceInstance.getName(), serviceInstance); 76 | try { 77 | serviceRegistry.registerService(serviceInstance); 78 | } catch (Exception e) { 79 | String message = String.format("[%s] Registration failed.", serviceInstance.getName()); 80 | throw new ServiceRegisterException(message, e); 81 | } 82 | } 83 | 84 | private ServiceInstance buildServiceInstance(ServiceProvider provider, Object bean){ 85 | ServiceInstance instance = new ServiceInstance(provider.name(), bean); 86 | instance.setDescription(provider.description()); 87 | instance.setClassType(provider.type()); 88 | return instance; 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /curator-example/src/test/java/com/github/loafer/curator/CuratorTest.java: -------------------------------------------------------------------------------- 1 | package com.github.loafer.curator; 2 | 3 | import org.apache.curator.RetryPolicy; 4 | import org.apache.curator.framework.CuratorFramework; 5 | import org.apache.curator.framework.CuratorFrameworkFactory; 6 | import org.apache.curator.framework.api.BackgroundCallback; 7 | import org.apache.curator.framework.api.CuratorEvent; 8 | import org.apache.curator.framework.api.UnhandledErrorListener; 9 | import org.apache.curator.framework.state.ConnectionState; 10 | import org.apache.curator.framework.state.ConnectionStateListener; 11 | import org.apache.curator.retry.ExponentialBackoffRetry; 12 | import org.apache.zookeeper.CreateMode; 13 | import org.apache.zookeeper.KeeperException.Code; 14 | 15 | /** 16 | * @author zhaojh. 17 | */ 18 | public class CuratorTest { 19 | public static void main(String[] args) throws Exception { 20 | RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 5); 21 | CuratorFramework client = CuratorFrameworkFactory.newClient("192.168.56.120:2181", retryPolicy); 22 | 23 | ConnectionStateListener stateListener = new ConnectionStateListener() { 24 | @Override 25 | public void stateChanged(CuratorFramework curatorFramework, ConnectionState connectionState) { 26 | if(connectionState == ConnectionState.CONNECTED){ 27 | System.out.println("connection."); 28 | } 29 | } 30 | }; 31 | client.getConnectionStateListenable().addListener(stateListener); 32 | 33 | 34 | UnhandledErrorListener errorListener = new UnhandledErrorListener() { 35 | @Override 36 | public void unhandledError(String s, Throwable throwable) { 37 | System.out.println("===>"+s); 38 | } 39 | }; 40 | client.getUnhandledErrorListenable().addListener(errorListener); 41 | 42 | 43 | client.start(); 44 | client.blockUntilConnected(); 45 | System.out.println("bala~~bala~~"); 46 | 47 | client.create().withMode(CreateMode.PERSISTENT).inBackground(new BackgroundCallback() { 48 | @Override 49 | public void processResult(CuratorFramework curatorFramework, CuratorEvent curatorEvent) throws Exception { 50 | // switch (Code.get(curatorEvent.getResultCode())) { 51 | // case NODEEXISTS: 52 | // System.out.println(curatorEvent.getPath() + " already created."); 53 | // break; 54 | // } 55 | 56 | switch (curatorEvent.getType()){ 57 | case CREATE: 58 | System.out.println(curatorEvent.getPath() + " already created."); 59 | break; 60 | } 61 | } 62 | }).forPath("/curator"); 63 | 64 | System.out.println("wait"); 65 | Thread.sleep(5000); 66 | System.out.println("wakeup"); 67 | 68 | client.create().withMode(CreateMode.PERSISTENT).inBackground(new BackgroundCallback() { 69 | @Override 70 | public void processResult(CuratorFramework curatorFramework, CuratorEvent curatorEvent) throws Exception { 71 | switch (Code.get(curatorEvent.getResultCode())) { 72 | case NODEEXISTS: 73 | System.out.println(curatorEvent.getPath() + " already created."); 74 | break; 75 | } 76 | } 77 | }).forPath("/curator/clients"); 78 | client.create().withMode(CreateMode.EPHEMERAL_SEQUENTIAL).forPath("/curator/clients/client-"); 79 | System.in.read(); 80 | client.close(); 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /master-worker-example/src/main/java/com/github/loafer/zookeeper/example/Master.java: -------------------------------------------------------------------------------- 1 | package com.github.loafer.zookeeper.example; 2 | 3 | import org.apache.zookeeper.*; 4 | import org.apache.zookeeper.AsyncCallback.StringCallback; 5 | import org.apache.zookeeper.AsyncCallback.DataCallback; 6 | import org.apache.zookeeper.AsyncCallback.StatCallback; 7 | import org.apache.zookeeper.AsyncCallback.ChildrenCallback; 8 | import org.apache.zookeeper.ZooDefs.Ids; 9 | import org.apache.zookeeper.data.Stat; 10 | import org.apache.zookeeper.KeeperException.Code; 11 | import org.slf4j.Logger; 12 | import org.slf4j.LoggerFactory; 13 | 14 | import java.io.IOException; 15 | import java.util.List; 16 | 17 | /** 18 | * @author zhaojh. 19 | */ 20 | public class Master implements Watcher { 21 | private static Logger logger = LoggerFactory.getLogger(Master.class); 22 | private String hostport; 23 | private String masterName; 24 | private ZooKeeper zk; 25 | private boolean leader; 26 | 27 | public Master(String hostport, String masterName) { 28 | this.hostport = hostport; 29 | this.masterName = masterName; 30 | } 31 | 32 | @Override 33 | public void process(WatchedEvent event) { 34 | System.out.println(event.toString()); 35 | } 36 | 37 | public void startZK() throws IOException { 38 | zk = new ZooKeeper(hostport, 2000, this); 39 | } 40 | 41 | public void stopZK() throws InterruptedException { 42 | zk.close(); 43 | } 44 | 45 | public void runForMaster(){ 46 | zk.create( 47 | "/master", 48 | masterName.getBytes(), 49 | Ids.OPEN_ACL_UNSAFE, 50 | CreateMode.EPHEMERAL, 51 | creatMasterCallback, 52 | null 53 | ); 54 | } 55 | 56 | public void bootstrap(){ 57 | createParentNode("/workers", new byte[0]); 58 | createParentNode("/assign", new byte[0]); 59 | createParentNode("/tasks", new byte[0]); 60 | createParentNode("/status", new byte[0]); 61 | } 62 | 63 | private void createParentNode(String path, byte[] data){ 64 | zk.create( 65 | path, 66 | data, 67 | Ids.OPEN_ACL_UNSAFE, 68 | CreateMode.PERSISTENT, 69 | createParentNodeCallback, 70 | data 71 | ); 72 | } 73 | 74 | private StringCallback createParentNodeCallback = new StringCallback() { 75 | @Override 76 | public void processResult(int rc, String path, Object ctx, String name) { 77 | switch (Code.get(rc)){ 78 | case CONNECTIONLOSS: 79 | createParentNode(path, (byte[]) ctx); 80 | break; 81 | case OK: 82 | logger.info("===> [{}]{} created.", masterName, path); 83 | break; 84 | case NODEEXISTS: 85 | logger.info("===> [{}]{} already registered.", masterName, path); 86 | break; 87 | default: 88 | logger.info("===> [{}]Something went wrong."); 89 | } 90 | } 91 | }; 92 | 93 | private void checkMaster(){ 94 | zk.getData("/master", true, checkMasterCallback, null); 95 | } 96 | 97 | private DataCallback checkMasterCallback = new DataCallback() { 98 | @Override 99 | public void processResult(int rc, String path, Object ctx, byte[] data, Stat stat) { 100 | switch (Code.get(rc)){ 101 | case CONNECTIONLOSS: 102 | checkMaster(); 103 | break; 104 | case NONODE: 105 | runForMaster(); 106 | break; 107 | } 108 | } 109 | }; 110 | 111 | private void watchMaster(){ 112 | zk.exists( 113 | "/master", 114 | masterWatcher, 115 | masterExistsCallback, 116 | null 117 | ); 118 | } 119 | 120 | private Watcher masterWatcher = new Watcher() { 121 | @Override 122 | public void process(WatchedEvent event) { 123 | switch (event.getType()){ 124 | case NodeDeleted: 125 | runForMaster(); 126 | break; 127 | } 128 | } 129 | }; 130 | 131 | private StatCallback masterExistsCallback = new StatCallback() { 132 | @Override 133 | public void processResult(int rc, String path, Object ctx, Stat stat) { 134 | switch (Code.get(rc)){ 135 | case CONNECTIONLOSS: 136 | watchMaster(); 137 | break; 138 | case OK: 139 | if(stat == null){ 140 | runForMaster(); 141 | } 142 | break; 143 | default: 144 | checkMaster(); 145 | break; 146 | } 147 | } 148 | }; 149 | 150 | private void getWorkers(){ 151 | zk.getChildren( 152 | "/workers", 153 | workersChangeWatcher, 154 | workersGetChildrenCallback, 155 | null 156 | ); 157 | } 158 | 159 | private Watcher workersChangeWatcher = new Watcher() { 160 | @Override 161 | public void process(WatchedEvent event) { 162 | switch (event.getType()){ 163 | case NodeChildrenChanged: 164 | getWorkers(); 165 | break; 166 | } 167 | } 168 | }; 169 | 170 | private ChildrenCallback workersGetChildrenCallback = new ChildrenCallback() { 171 | @Override 172 | public void processResult(int rc, String path, Object ctx, List children) { 173 | switch (Code.get(rc)){ 174 | case CONNECTIONLOSS: 175 | getWorkers(); 176 | break; 177 | case OK: 178 | //分配worker 179 | logger.info("===> Successfully got a list of workers: {} workers.", children.size()); 180 | break; 181 | default: 182 | logger.info("===> get Workers fail."); 183 | break; 184 | } 185 | } 186 | }; 187 | 188 | private StringCallback creatMasterCallback = new StringCallback() { 189 | @Override 190 | public void processResult(int rc, String path, Object ctx, String name) { 191 | switch (Code.get(rc)){ 192 | case CONNECTIONLOSS: 193 | checkMaster(); 194 | break; 195 | case OK: 196 | leader = true; 197 | logger.info("===> [{}] {} created.", masterName, name); 198 | getWorkers(); 199 | break; 200 | case NODEEXISTS: 201 | watchMaster(); 202 | break; 203 | default: 204 | leader = false; 205 | } 206 | 207 | logger.info("===> [{}] {}", masterName, Code.get(rc)); 208 | if(leader){ 209 | logger.info("===> [{}] I'm the leader.", masterName); 210 | }else{ 211 | logger.info("===> [{}] Someone else is the leader. I'm backup", masterName); 212 | } 213 | } 214 | }; 215 | 216 | 217 | public static void main(String[] args) throws IOException, InterruptedException { 218 | Master master = new Master("192.168.56.120:2181/master-workers", "Master One"); 219 | master.startZK(); 220 | Thread.sleep(1000); 221 | master.runForMaster(); 222 | 223 | System.in.read(); 224 | master.stopZK(); 225 | } 226 | } 227 | -------------------------------------------------------------------------------- /zookeeper-client-example/src/main/java/com/github/loafer/rpc/ServiceRegistryImpl.java: -------------------------------------------------------------------------------- 1 | package com.github.loafer.rpc; 2 | 3 | import com.fasterxml.jackson.databind.ObjectMapper; 4 | import org.apache.curator.RetryPolicy; 5 | import org.apache.curator.framework.CuratorFramework; 6 | import org.apache.curator.framework.CuratorFrameworkFactory; 7 | import org.apache.curator.framework.api.BackgroundCallback; 8 | import org.apache.curator.framework.api.CuratorEvent; 9 | import org.apache.curator.retry.ExponentialBackoffRetry; 10 | import org.apache.zookeeper.CreateMode; 11 | import org.apache.zookeeper.KeeperException.Code; 12 | import org.slf4j.Logger; 13 | import org.slf4j.LoggerFactory; 14 | import org.springframework.beans.factory.DisposableBean; 15 | import org.springframework.beans.factory.InitializingBean; 16 | 17 | /** 18 | * /serviceRegistry 19 | * |-{serviceName} 20 | * |-providers 21 | * | |-provider-01 22 | * | |-provider-02 23 | * | 24 | * |-consumers 25 | * |-consumer-01 26 | * |-consumer-02 27 | * 28 | * @author zhaojh. 29 | */ 30 | public class ServiceRegistryImpl implements ServiceRegistry, InitializingBean, DisposableBean{ 31 | private static Logger logger = LoggerFactory.getLogger(ServiceRegistryImpl.class); 32 | private static final String SERVICE_REGISTRY_BASE_PATH = "/serviceRegistry"; 33 | private static final String SERVICE_PATH = SERVICE_REGISTRY_BASE_PATH + "/%s"; 34 | private static final String SERVICE_PROVIDERS_PATH = SERVICE_PATH +"/providers"; 35 | private static final String SERVICE_CONSUMERS_PATH = SERVICE_PATH +"/consumers"; 36 | private static final String SERVICE_PROVIDER_PREFIX = SERVICE_PROVIDERS_PATH + "/provider-"; 37 | 38 | private String registryAddress; 39 | private CuratorFramework curatorFramework; 40 | private ObjectMapper mapper = new ObjectMapper(); 41 | 42 | public ServiceRegistryImpl(String registryAddress) { 43 | this.registryAddress = registryAddress; 44 | } 45 | 46 | @Override 47 | public void destroy() throws Exception { 48 | disconnectZK(); 49 | } 50 | 51 | @Override 52 | public void afterPropertiesSet() throws Exception { 53 | bootstrap(); 54 | } 55 | 56 | @Override 57 | public void registerService(ServiceInstance serviceInstance) throws Exception { 58 | checkServiceZnode(serviceInstance); 59 | } 60 | 61 | private void connectZK() throws Exception { 62 | RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3); 63 | curatorFramework = CuratorFrameworkFactory.newClient(registryAddress, retryPolicy); 64 | curatorFramework.start(); 65 | } 66 | 67 | private void disconnectZK(){ 68 | logger.info("disconnect"); 69 | curatorFramework.close(); 70 | } 71 | 72 | private void bootstrap() throws Exception { 73 | connectZK(); 74 | checkServiceRegistryZnode(); 75 | } 76 | 77 | private BackgroundCallback checkServiceRegistryCallback = new BackgroundCallback() { 78 | @Override 79 | public void processResult(CuratorFramework curatorFramework, CuratorEvent curatorEvent) 80 | throws Exception { 81 | switch (Code.get(curatorEvent.getResultCode())) { 82 | case NONODE: 83 | createServiceRegistryZNode(); 84 | break; 85 | } 86 | } 87 | }; 88 | 89 | private void checkServiceRegistryZnode() throws Exception { 90 | curatorFramework 91 | .getData() 92 | .inBackground(checkServiceRegistryCallback) 93 | .forPath(SERVICE_REGISTRY_BASE_PATH); 94 | } 95 | 96 | private BackgroundCallback createServiceRegistryCallback = new BackgroundCallback() { 97 | @Override 98 | public void processResult(CuratorFramework curatorFramework, 99 | CuratorEvent curatorEvent) throws Exception { 100 | switch (Code.get(curatorEvent.getResultCode())) { 101 | case NODEEXISTS: 102 | logger.info("===>[{}] already created.", curatorEvent.getPath()); 103 | break; 104 | } 105 | } 106 | }; 107 | private void createServiceRegistryZNode() throws Exception { 108 | curatorFramework 109 | .create() 110 | .withMode(CreateMode.PERSISTENT) 111 | .inBackground(createServiceRegistryCallback) 112 | .forPath(SERVICE_REGISTRY_BASE_PATH, new byte[0]); 113 | } 114 | 115 | private BackgroundCallback checkServiceCallback = new BackgroundCallback() { 116 | @Override 117 | public void processResult(CuratorFramework curatorFramework, 118 | CuratorEvent curatorEvent) throws Exception { 119 | 120 | ServiceInstance serviceInstance = (ServiceInstance) curatorEvent.getContext(); 121 | switch (Code.get(curatorEvent.getResultCode())){ 122 | case NONODE: 123 | createServiceZNode(serviceInstance); 124 | break; 125 | case OK: 126 | logger.info("===>[{}] already created.", curatorEvent.getPath()); 127 | createProvidersZNode(serviceInstance); 128 | createConsumersZNode(serviceInstance); 129 | break; 130 | } 131 | } 132 | }; 133 | 134 | private void checkServiceZnode(final ServiceInstance serviceInstance) throws Exception { 135 | String serviceName = serviceInstance.getName(); 136 | String path = String.format(SERVICE_PATH, serviceName); 137 | logger.info("===>check [{}].", path); 138 | curatorFramework 139 | .getData() 140 | .inBackground(checkServiceCallback, serviceInstance) 141 | .forPath(path); 142 | } 143 | 144 | private BackgroundCallback createServiceCallback = new BackgroundCallback() { 145 | @Override 146 | public void processResult(CuratorFramework curatorFramework, 147 | CuratorEvent curatorEvent) throws Exception { 148 | ServiceInstance serviceInstance = (ServiceInstance) curatorEvent.getContext(); 149 | switch (Code.get(curatorEvent.getResultCode())) { 150 | case NODEEXISTS: 151 | logger.info("===>[{}] already created.", curatorEvent.getPath()); 152 | break; 153 | case OK: 154 | logger.info("===>[{}] created.", curatorEvent.getPath()); 155 | createProvidersZNode(serviceInstance); 156 | createConsumersZNode(serviceInstance); 157 | break; 158 | } 159 | } 160 | }; 161 | private void createServiceZNode(final ServiceInstance serviceInstance) throws Exception { 162 | final String serviceName = serviceInstance.getName(); 163 | String path = String.format(SERVICE_PATH, serviceName); 164 | logger.info("===>creating [{}].", path); 165 | curatorFramework 166 | .create() 167 | .withMode(CreateMode.PERSISTENT) 168 | .inBackground(createServiceCallback, serviceInstance) 169 | .forPath(path); 170 | } 171 | 172 | private BackgroundCallback createProvidersCallback = new BackgroundCallback() { 173 | @Override 174 | public void processResult(CuratorFramework curatorFramework, 175 | CuratorEvent curatorEvent) throws Exception { 176 | ServiceInstance serviceInstance = (ServiceInstance) curatorEvent.getContext(); 177 | switch (Code.get(curatorEvent.getResultCode())){ 178 | case OK: 179 | logger.info("===>[{}] created.", curatorEvent.getPath()); 180 | createProviderZNode(serviceInstance); 181 | break; 182 | case NODEEXISTS: 183 | logger.info("===>[{}] already created.", curatorEvent.getPath()); 184 | createProviderZNode(serviceInstance); 185 | break; 186 | } 187 | } 188 | }; 189 | 190 | private void createProvidersZNode(final ServiceInstance serviceInstance) throws Exception { 191 | String serviceName = serviceInstance.getName(); 192 | String path = String.format(SERVICE_PROVIDERS_PATH, serviceName); 193 | logger.info("===>creating [{}].", path); 194 | curatorFramework 195 | .create() 196 | .withMode(CreateMode.PERSISTENT) 197 | .inBackground(createProvidersCallback, serviceInstance) 198 | .forPath(path); 199 | } 200 | 201 | private BackgroundCallback createConsumersCallback = new BackgroundCallback() { 202 | @Override 203 | public void processResult(CuratorFramework curatorFramework, 204 | CuratorEvent curatorEvent) throws Exception { 205 | switch (Code.get(curatorEvent.getResultCode())){ 206 | case OK: 207 | logger.info("===>[{}] created.", curatorEvent.getPath()); 208 | break; 209 | case NODEEXISTS: 210 | logger.info("===>[{}] already created.", curatorEvent.getPath()); 211 | break; 212 | } 213 | } 214 | }; 215 | private void createConsumersZNode(final ServiceInstance serviceInstance) throws Exception { 216 | String serviceName = serviceInstance.getName(); 217 | String path = String.format(SERVICE_CONSUMERS_PATH, serviceName); 218 | logger.info("===>creating [{}].", path); 219 | curatorFramework 220 | .create() 221 | .withMode(CreateMode.PERSISTENT) 222 | .inBackground(createConsumersCallback) 223 | .forPath(path); 224 | } 225 | 226 | private void createProviderZNode(final ServiceInstance serviceInstance) throws Exception { 227 | String serviceName = serviceInstance.getName(); 228 | String path = String.format(SERVICE_PROVIDER_PREFIX, serviceName); 229 | logger.info("===>creating [{}]", path); 230 | curatorFramework 231 | .create() 232 | .withMode(CreateMode.EPHEMERAL_SEQUENTIAL) 233 | .inBackground() 234 | .forPath(path, mapper.writeValueAsBytes(serviceInstance)); 235 | } 236 | } 237 | --------------------------------------------------------------------------------