├── README.md ├── nredis-proxy-commons ├── .classpath ├── .gitignore ├── .project ├── .settings │ ├── org.eclipse.core.resources.prefs │ ├── org.eclipse.jdt.core.prefs │ ├── org.eclipse.m2e.core.prefs │ ├── org.eclipse.wst.common.component │ ├── org.eclipse.wst.common.project.facet.core.xml │ └── org.eclipse.wst.validation.prefs ├── pom.xml └── src │ └── main │ └── java │ └── com │ └── opensource │ └── netty │ └── redis │ └── proxy │ └── commons │ ├── algorithm │ ├── Hashing.java │ └── impl │ │ ├── ConsistentHash.java │ │ ├── MurmurHash.java │ │ ├── RoundRobinHash.java │ │ └── support │ │ ├── RedisWeight.java │ │ └── SafeEncoder.java │ ├── conf │ └── Configuration.java │ ├── constants │ ├── LBRedisProxyErrorMsgConstant.java │ └── RedisConstants.java │ ├── exception │ ├── AbstractLBRedisProxyException.java │ ├── LBRedisProxyErrorMsg.java │ ├── LBRedisProxyFrameworkException.java │ └── RedisException.java │ └── utils │ ├── ArrayUtils.java │ ├── CharsetUtils.java │ ├── ConcurrentHashSet.java │ ├── ProtoUtil.java │ ├── ProtoUtils.java │ ├── ReflectUtils.java │ ├── RequestIdGeneratorUtils.java │ └── StringUtils.java ├── nredis-proxy-core ├── .classpath ├── .gitignore ├── .project ├── .settings │ ├── org.eclipse.core.resources.prefs │ ├── org.eclipse.jdt.core.prefs │ ├── org.eclipse.m2e.core.prefs │ ├── org.eclipse.wst.common.component │ ├── org.eclipse.wst.common.project.facet.core.xml │ └── org.eclipse.wst.validation.prefs ├── pom.xml └── src │ ├── .DS_Store │ └── main │ └── java │ └── com │ └── opensource │ └── netty │ └── redis │ └── proxy │ └── core │ ├── client │ ├── Client.java │ └── impl │ │ ├── AbstractClient.java │ │ └── AbstractPoolClient.java │ ├── cluster │ ├── LoadBalance.java │ └── impl │ │ ├── AbstractLoadBalance.java │ │ ├── ConsistentHashLoadBalance.java │ │ ├── RoundRobinLoadBalance.java │ │ └── support │ │ └── RedisQuestBean.java │ ├── command │ ├── IRedisCommand.java │ └── impl │ │ ├── RedisCommand.java │ │ └── ShutdownCommand.java │ ├── config │ ├── LBRedisServerMasterCluster.java │ └── support │ │ ├── LBRedisServerBean.java │ │ └── LBRedisServerClusterBean.java │ ├── connection │ ├── IConnection.java │ ├── IConnectionCallBack.java │ └── impl │ │ └── RedisConnectionCallBack.java │ ├── enums │ ├── ChannelState.java │ ├── RedisCommandEnums.java │ ├── RedisProxyParamType.java │ ├── ReplyState.java │ ├── RequestState.java │ ├── Type.java │ └── ZkNodeType.java │ ├── listen │ ├── IRegistryListen.java │ └── impl │ │ └── AbstractRegistryListenImpl.java │ ├── log │ ├── ILogService.java │ └── impl │ │ ├── LogService.java │ │ └── LoggerUtils.java │ ├── pool │ └── utils │ │ └── LBRedisProxyChannelPoolUtils.java │ ├── protocol │ ├── RedisReplyDecoder.java │ ├── RedisReplyEncoder.java │ ├── RedisRequestDecoder.java │ └── RedisRequestEncoder.java │ ├── registry │ ├── NotifyListener.java │ ├── Registry.java │ ├── RegistryFactory.java │ ├── RegistryService.java │ └── impl │ │ ├── AbstractRegistry.java │ │ ├── AbstractRegistryFactory.java │ │ └── support │ │ └── ZkUtils.java │ ├── reply │ ├── IRedisReply.java │ └── impl │ │ ├── AbstractRedisReply.java │ │ ├── BulkRedisReply.java │ │ ├── CommonRedisReply.java │ │ ├── ErrorRedisReply.java │ │ ├── IntegerRedisReply.java │ │ ├── MultyBulkRedisReply.java │ │ └── StatusRedisReply.java │ └── url │ └── RedisProxyURL.java ├── nredis-proxy-failover ├── .classpath ├── .gitignore ├── .project ├── .settings │ ├── .jsdtscope │ ├── org.eclipse.core.resources.prefs │ ├── org.eclipse.jdt.core.prefs │ ├── org.eclipse.m2e.core.prefs │ ├── org.eclipse.wst.common.component │ ├── org.eclipse.wst.common.project.facet.core.xml │ ├── org.eclipse.wst.jsdt.ui.superType.container │ ├── org.eclipse.wst.jsdt.ui.superType.name │ └── org.eclipse.wst.validation.prefs ├── pom.xml └── src │ └── main │ ├── java │ └── com │ │ └── opensource │ │ └── netty │ │ └── redis │ │ └── proxy │ │ └── monitor │ │ └── spring │ │ ├── bean │ │ └── RedisMonitorConfiguration.java │ │ ├── helper │ │ ├── RedisMonitorConfigurationHelper.java │ │ ├── SpringFactory.java │ │ └── SuperClassReflectionUtils.java │ │ └── job │ │ └── RedisMasterSlaveMonitorJob.java │ ├── resources │ ├── applicationContext.xml │ ├── log4j.properties │ └── timer.xml │ └── webapp │ ├── WEB-INF │ └── web.xml │ └── index.jsp ├── nredis-proxy-net ├── .classpath ├── .gitignore ├── .project ├── .settings │ ├── org.eclipse.core.resources.prefs │ ├── org.eclipse.jdt.core.prefs │ └── org.eclipse.m2e.core.prefs ├── pom.xml └── src │ └── main │ └── java │ └── com │ └── opensource │ └── netty │ └── redis │ └── proxy │ └── net │ ├── client │ ├── LBRedisClient.java │ ├── LBRedisConnection.java │ ├── LBRedisConnectionFactory.java │ └── support │ │ ├── LBRedisClientInHandler.java │ │ └── LBRedisClientOutHandler.java │ └── server │ ├── LBRedisServer.java │ └── support │ └── LBRedisServerHandler.java ├── nredis-proxy-pool ├── .classpath ├── .gitignore ├── .project ├── .settings │ ├── org.eclipse.core.resources.prefs │ ├── org.eclipse.jdt.core.prefs │ ├── org.eclipse.m2e.core.prefs │ ├── org.eclipse.wst.common.component │ ├── org.eclipse.wst.common.project.facet.core.xml │ └── org.eclipse.wst.validation.prefs ├── pom.xml └── src │ └── main │ └── java │ └── com │ └── opensource │ └── netty │ └── redis │ └── proxy │ └── pool │ ├── LBRedisProxyIdleEntriesQueue.java │ ├── LBRedisProxyPool.java │ ├── LBRedisProxyPoolEntry.java │ ├── LBRedisProxyPoolEntryFactory.java │ ├── LBRedisProxyPooledObjectFactory.java │ ├── commons │ ├── LBRedisProxyPoolConfig.java │ ├── LBRedisProxyPoolEntryState.java │ └── Pool.java │ ├── exception │ ├── LBRedisProxyPoolException.java │ └── LBRedisProxyPoolPropertyValidationException.java │ └── impl │ ├── LBRedisProxyBasicPool.java │ ├── LBRedisProxyBasicPoolEntry.java │ ├── LBRedisProxyPoolBasicEntryFactory.java │ └── LBRedisProxyPoolBasicIdleEntriesQueue.java ├── nredis-proxy-register ├── .classpath ├── .gitignore ├── .project ├── .settings │ ├── org.eclipse.core.resources.prefs │ ├── org.eclipse.jdt.core.prefs │ ├── org.eclipse.m2e.core.prefs │ ├── org.eclipse.wst.common.component │ ├── org.eclipse.wst.common.project.facet.core.xml │ └── org.eclipse.wst.validation.prefs ├── pom.xml └── src │ └── main │ └── java │ ├── com │ └── opensource │ │ └── netty │ │ └── redis │ │ └── proxy │ │ └── zk │ │ └── registry │ │ ├── ZookeeperRegistry.java │ │ ├── ZookeeperRegistryFactory.java │ │ └── listen │ │ └── ZookeeperRegistryListen.java │ └── org │ └── I0Itec │ └── zkclient │ ├── ContentWatcher.java │ ├── DataUpdater.java │ ├── DistributedQueue.java │ ├── ExceptionUtil.java │ ├── Gateway.java │ ├── GatewayThread.java │ ├── Holder.java │ ├── IDefaultNameSpace.java │ ├── IZkChildListener.java │ ├── IZkConnection.java │ ├── IZkDataListener.java │ ├── IZkStateListener.java │ ├── InMemoryConnection.java │ ├── NetworkUtil.java │ ├── ZkClient.java │ ├── ZkConnection.java │ ├── ZkEventThread.java │ ├── ZkLock.java │ ├── ZkServer.java │ ├── exception │ ├── ZkBadVersionException.java │ ├── ZkException.java │ ├── ZkInterruptedException.java │ ├── ZkMarshallingError.java │ ├── ZkNoNodeException.java │ ├── ZkNodeExistsException.java │ └── ZkTimeoutException.java │ ├── serialize │ ├── BytesPushThroughSerializer.java │ ├── SerializableSerializer.java │ ├── TcclAwareObjectIputStream.java │ └── ZkSerializer.java │ └── util │ └── ZkPathUtil.java ├── nredis-proxy-sample ├── .classpath ├── .gitignore ├── .project ├── .settings │ ├── org.eclipse.core.resources.prefs │ ├── org.eclipse.jdt.core.prefs │ └── org.eclipse.m2e.core.prefs ├── log │ └── hedis.log ├── pom.xml └── src │ ├── main │ ├── assembly │ │ └── assembly.xml │ ├── deploy │ │ ├── package-dependency.properties │ │ └── single.sh │ ├── java │ │ └── com │ │ │ └── opensource │ │ │ └── netty │ │ │ └── redis │ │ │ └── proxy │ │ │ └── sample │ │ │ ├── ClassRoom.java │ │ │ ├── RedisClientDemo.java │ │ │ ├── RedisProxyServerBootStrap.java │ │ │ └── ShortUrl.java │ └── resources │ │ ├── log4j.properties │ │ └── redisProxy.xml │ └── test │ └── java │ └── org │ └── nredis │ └── proxy │ └── sample │ └── AppTest.java ├── nredis-proxy-spring ├── .classpath ├── .gitignore ├── .project ├── .settings │ ├── org.eclipse.core.resources.prefs │ ├── org.eclipse.jdt.core.prefs │ └── org.eclipse.m2e.core.prefs ├── pom.xml └── src │ └── main │ ├── java │ └── com │ │ └── opensource │ │ └── netty │ │ └── redis │ │ └── proxy │ │ └── spring │ │ ├── handler │ │ └── RedisProxyHandlerSupport.java │ │ └── schema │ │ ├── RedisProxyNodeParser.java │ │ └── support │ │ ├── RedisProxyCluster.java │ │ ├── RedisProxyConstant.java │ │ ├── RedisProxyMaster.java │ │ └── RedisProxyNode.java │ └── resources │ └── META-INF │ ├── redisProxy.xsd │ ├── spring.handlers │ └── spring.schemas └── pom.xml /README.md: -------------------------------------------------------------------------------- 1 | nredis-proxy 是一个以redis 协议为主的高性能稳定的代理中间件服务,不侵入业务代码,与业务毫无联系,不需要改任何应用代码,天然支持分布式部署。 2 | 3 | 一:功能特点: 4 | 5 | 1:自带连接池,性能高效 6 | 7 | 2:提供分片策略,扩展性强,可自定义分片算法 8 | 9 | 3:提供读写分离,一主多从,从按照权重读取 10 | 11 | 4:提供自动监听功能,主挂了,提供选举算法,从作为主 12 | 13 | 5:可HA分布式部署,节点随意扩展 14 | 15 | 二:nredis-proxy 架构图 16 | 17 | ![输入图片说明](http://git.oschina.net/uploads/images/2016/1110/000750_ed0b1d9f_54128.png "在这里输入图片标题") 18 | 19 | 三:nredis-proxy 部署架构图 20 | 21 | ![输入图片说明](http://git.oschina.net/uploads/images/2016/1110/000104_44f5a5cb_54128.png "在这里输入图片标题") 22 | 23 | 详细文档地址 :[https://my.oschina.net/liubingsmile/blog/786465](https://my.oschina.net/liubingsmile/blog/786465) -------------------------------------------------------------------------------- /nredis-proxy-commons/.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /nredis-proxy-commons/.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | -------------------------------------------------------------------------------- /nredis-proxy-commons/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | nredis-proxy-commons 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.wst.common.project.facet.core.builder 10 | 11 | 12 | 13 | 14 | org.eclipse.jdt.core.javabuilder 15 | 16 | 17 | 18 | 19 | org.eclipse.wst.validation.validationbuilder 20 | 21 | 22 | 23 | 24 | org.eclipse.m2e.core.maven2Builder 25 | 26 | 27 | 28 | 29 | 30 | org.eclipse.jem.workbench.JavaEMFNature 31 | org.eclipse.wst.common.modulecore.ModuleCoreNature 32 | org.eclipse.jdt.core.javanature 33 | org.eclipse.m2e.core.maven2Nature 34 | org.eclipse.wst.common.project.facet.core.nature 35 | 36 | 37 | -------------------------------------------------------------------------------- /nredis-proxy-commons/.settings/org.eclipse.core.resources.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | encoding//src/main/java=UTF-8 3 | encoding/=UTF-8 4 | -------------------------------------------------------------------------------- /nredis-proxy-commons/.settings/org.eclipse.jdt.core.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled 3 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.7 4 | org.eclipse.jdt.core.compiler.compliance=1.7 5 | org.eclipse.jdt.core.compiler.problem.assertIdentifier=error 6 | org.eclipse.jdt.core.compiler.problem.enumIdentifier=error 7 | org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning 8 | org.eclipse.jdt.core.compiler.source=1.7 9 | -------------------------------------------------------------------------------- /nredis-proxy-commons/.settings/org.eclipse.m2e.core.prefs: -------------------------------------------------------------------------------- 1 | activeProfiles= 2 | eclipse.preferences.version=1 3 | resolveWorkspaceProjects=true 4 | version=1 5 | -------------------------------------------------------------------------------- /nredis-proxy-commons/.settings/org.eclipse.wst.common.component: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /nredis-proxy-commons/.settings/org.eclipse.wst.common.project.facet.core.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /nredis-proxy-commons/.settings/org.eclipse.wst.validation.prefs: -------------------------------------------------------------------------------- 1 | disabled=06target 2 | eclipse.preferences.version=1 3 | -------------------------------------------------------------------------------- /nredis-proxy-commons/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.opensource 7 | nredis-proxy 8 | 1.0 9 | 10 | com.opensource 11 | nredis-proxy-commons 12 | 1.0 13 | nredis-proxy-commons 14 | http://maven.apache.org 15 | 16 | UTF-8 17 | 18 | 19 | 20 | junit 21 | junit 22 | test 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /nredis-proxy-commons/src/main/java/com/opensource/netty/redis/proxy/commons/algorithm/Hashing.java: -------------------------------------------------------------------------------- 1 | package com.opensource.netty.redis.proxy.commons.algorithm; 2 | 3 | import java.security.MessageDigest; 4 | import java.security.NoSuchAlgorithmException; 5 | 6 | import com.opensource.netty.redis.proxy.commons.algorithm.impl.support.SafeEncoder; 7 | 8 | 9 | /** 10 | * hash 算法接口 11 | * @author liubing 12 | * 13 | */ 14 | public interface Hashing { 15 | 16 | public ThreadLocal md5Holder = new ThreadLocal(); 17 | 18 | public static final Hashing MD5 = new Hashing() { 19 | public long hash(String key) { 20 | return hash(SafeEncoder.encode(key)); 21 | } 22 | 23 | public long hash(byte[] key) { 24 | try { 25 | if (md5Holder.get() == null) { 26 | md5Holder.set(MessageDigest.getInstance("MD5")); 27 | } 28 | } catch (NoSuchAlgorithmException e) { 29 | throw new IllegalStateException("++++ no md5 algorythm found"); 30 | } 31 | MessageDigest md5 = md5Holder.get(); 32 | 33 | md5.reset(); 34 | md5.update(key); 35 | byte[] bKey = md5.digest(); 36 | long res = ((long) (bKey[3] & 0xFF) << 24) 37 | | ((long) (bKey[2] & 0xFF) << 16) 38 | | ((long) (bKey[1] & 0xFF) << 8) | (long) (bKey[0] & 0xFF); 39 | return res; 40 | } 41 | }; 42 | 43 | public long hash(String key); 44 | 45 | public long hash(byte[] key); 46 | 47 | } 48 | -------------------------------------------------------------------------------- /nredis-proxy-commons/src/main/java/com/opensource/netty/redis/proxy/commons/algorithm/impl/ConsistentHash.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package com.opensource.netty.redis.proxy.commons.algorithm.impl; 5 | 6 | import java.util.Collection; 7 | import java.util.SortedMap; 8 | import java.util.TreeMap; 9 | 10 | import com.opensource.netty.redis.proxy.commons.algorithm.Hashing; 11 | 12 | 13 | /** 14 | * @author liubing 15 | * 16 | */ 17 | public class ConsistentHash { 18 | 19 | private final Hashing hash; 20 | private final int numberOfReplicas; 21 | private final SortedMap circle = new TreeMap(); 22 | 23 | public ConsistentHash(Hashing hash, int numberOfReplicas, 24 | Collection nodes) { 25 | super(); 26 | this.hash = hash; 27 | this.numberOfReplicas = numberOfReplicas; 28 | for (T node : nodes) { 29 | add(node); 30 | } 31 | } 32 | 33 | /** 34 | * 增加真实机器节点 35 | * 36 | * @param node 37 | */ 38 | public void add(T node) { 39 | for (int i = 0; i < this.numberOfReplicas; i++) { 40 | circle.put(this.hash.hash(node.toString() + i), node); 41 | } 42 | } 43 | 44 | /** 45 | * 删除真实机器节点 46 | * 47 | * @param node 48 | */ 49 | public void remove(T node) { 50 | for (int i = 0; i < this.numberOfReplicas; i++) { 51 | circle.remove(this.hash.hash(node.toString() + i)); 52 | } 53 | } 54 | 55 | /** 56 | * 取得真实机器节点 57 | * 58 | * @param key 59 | * @return 60 | */ 61 | public T get(String key) { 62 | if (circle.isEmpty()) { 63 | return null; 64 | } 65 | long hash = this.hash.hash(key); 66 | if (!circle.containsKey(hash)) { 67 | SortedMap tailMap = circle.tailMap(hash);// 沿环的顺时针找到一个虚拟节点 68 | hash = tailMap.isEmpty() ? circle.firstKey() : tailMap.firstKey(); 69 | } 70 | return circle.get(hash); // 返回该虚拟节点对应的真实机器节点的信息 71 | } 72 | 73 | public T getBytes(byte[] key) { 74 | if (circle.isEmpty()) { 75 | return null; 76 | } 77 | long hash = this.hash.hash(key); 78 | if (!circle.containsKey(hash)) { 79 | SortedMap tailMap = circle.tailMap(hash);// 沿环的顺时针找到一个虚拟节点 80 | hash = tailMap.isEmpty() ? circle.firstKey() : tailMap.firstKey(); 81 | } 82 | return circle.get(hash); // 返回该虚拟节点对应的真实机器节点的信息 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /nredis-proxy-commons/src/main/java/com/opensource/netty/redis/proxy/commons/algorithm/impl/RoundRobinHash.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package com.opensource.netty.redis.proxy.commons.algorithm.impl; 5 | 6 | import java.util.ArrayList; 7 | import java.util.HashMap; 8 | import java.util.Iterator; 9 | import java.util.List; 10 | import java.util.Map; 11 | import java.util.Random; 12 | import java.util.Set; 13 | 14 | import com.opensource.netty.redis.proxy.commons.algorithm.impl.support.RedisWeight; 15 | 16 | /** 17 | * @author liubing 权重随机算法 18 | */ 19 | public class RoundRobinHash { 20 | 21 | public Map serverMap = new HashMap(); 22 | 23 | /** 24 | * 构造方法 25 | */ 26 | public RoundRobinHash(List list) { 27 | init(list); 28 | } 29 | 30 | /** 31 | * 初始化 32 | * 33 | */ 34 | private void init(List list) { 35 | for (T t : list) { 36 | RedisWeight redisWeight = (RedisWeight) t; 37 | serverMap.put(t, redisWeight.getWeight()); 38 | } 39 | } 40 | 41 | public T weightRandom() {// 随机权重算法 42 | Set keySet = serverMap.keySet(); 43 | Iterator iterator = keySet.iterator(); 44 | List serverList = new ArrayList(); 45 | while (iterator.hasNext()) { 46 | T server = iterator.next(); 47 | Integer weight = serverMap.get(server); 48 | for (int i = 0; i < weight; i++) { 49 | serverList.add(server); 50 | } 51 | } 52 | if(serverList!=null&&serverList.size()>0){ 53 | Random random = new Random(); 54 | int randomPos = random.nextInt(serverList.size()); 55 | 56 | T server = serverList.get(randomPos); 57 | return server; 58 | } 59 | return null; 60 | 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /nredis-proxy-commons/src/main/java/com/opensource/netty/redis/proxy/commons/algorithm/impl/support/RedisWeight.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package com.opensource.netty.redis.proxy.commons.algorithm.impl.support; 5 | 6 | /** 7 | * @author liubing 8 | * 9 | */ 10 | public interface RedisWeight { 11 | 12 | /** 13 | * 获取权重比例 14 | * @return 15 | */ 16 | public int getWeight(); 17 | 18 | 19 | } 20 | -------------------------------------------------------------------------------- /nredis-proxy-commons/src/main/java/com/opensource/netty/redis/proxy/commons/algorithm/impl/support/SafeEncoder.java: -------------------------------------------------------------------------------- 1 | package com.opensource.netty.redis.proxy.commons.algorithm.impl.support; 2 | 3 | import java.io.UnsupportedEncodingException; 4 | 5 | import com.opensource.netty.redis.proxy.commons.constants.RedisConstants; 6 | 7 | /** 8 | * 9 | * @author liubing 10 | * 11 | */ 12 | public class SafeEncoder { 13 | public static byte[][] encodeMany(final String... strs){ 14 | byte[][] many = new byte[strs.length][]; 15 | for(int i=0;i sizeTable[size]) 51 | size++; 52 | size++; 53 | if (originValue < 0) 54 | size++; 55 | 56 | int q, r; 57 | byte[] buf = new byte[size]; 58 | if (originValue < 0) { 59 | buf[0] = '-'; 60 | } 61 | int charPos = size; 62 | 63 | while (value >= 65536) { 64 | q = value / 100; 65 | r = value - ((q << 6) + (q << 5) + (q << 2)); 66 | value = q; 67 | buf[--charPos] = DigitOnes[r]; 68 | buf[--charPos] = DigitTens[r]; 69 | } 70 | 71 | for (;;) { 72 | q = (value * 52429) >>> (16 + 3); 73 | r = value - ((q << 3) + (q << 1)); 74 | buf[--charPos] = digits[r]; 75 | value = q; 76 | if (value == 0) 77 | break; 78 | } 79 | return buf; 80 | } 81 | 82 | public static byte[] buildErrorReplyBytes(String message) { 83 | return ("ERR " + message).getBytes(); 84 | } 85 | 86 | 87 | } 88 | -------------------------------------------------------------------------------- /nredis-proxy-commons/src/main/java/com/opensource/netty/redis/proxy/commons/utils/RequestIdGeneratorUtils.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2009-2016 Weibo, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.opensource.netty.redis.proxy.commons.utils; 18 | 19 | import java.util.concurrent.atomic.AtomicLong; 20 | 21 | 22 | /** 23 | * 通过requestId能够知道大致请求的时间 24 | * 25 | *
26 |  * 		目前是 currentTimeMillis * (2^20) + offset.incrementAndGet()
27 |  * 
28 |  * 		通过 requestId / (2^20 * 1000) 能够得到秒
29 |  *
30 |  * 
31 | * 32 | * @author liubing 33 | * 34 | */ 35 | public class RequestIdGeneratorUtils { 36 | protected static final AtomicLong offset = new AtomicLong(0); 37 | protected static final int BITS = 20; 38 | protected static final long MAX_COUNT_PER_MILLIS = 1 << BITS; 39 | 40 | 41 | /** 42 | * 获取 requestId 43 | * 44 | * @return 45 | */ 46 | public static long getRequestId() { 47 | long currentTime = System.currentTimeMillis(); 48 | long count = offset.incrementAndGet(); 49 | while(count >= MAX_COUNT_PER_MILLIS){ 50 | synchronized (RequestIdGeneratorUtils.class){ 51 | if(offset.get() >= MAX_COUNT_PER_MILLIS){ 52 | offset.set(0); 53 | } 54 | } 55 | count = offset.incrementAndGet(); 56 | } 57 | return (currentTime << BITS) + count; 58 | } 59 | 60 | public static long getRequestIdFromClient() { 61 | // TODO 上下文 requestid 62 | return 0; 63 | 64 | } 65 | 66 | } 67 | -------------------------------------------------------------------------------- /nredis-proxy-core/.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /nredis-proxy-core/.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | -------------------------------------------------------------------------------- /nredis-proxy-core/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | nredis-proxy-core 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.wst.common.project.facet.core.builder 10 | 11 | 12 | 13 | 14 | org.eclipse.jdt.core.javabuilder 15 | 16 | 17 | 18 | 19 | org.eclipse.wst.validation.validationbuilder 20 | 21 | 22 | 23 | 24 | org.eclipse.m2e.core.maven2Builder 25 | 26 | 27 | 28 | 29 | 30 | org.eclipse.jem.workbench.JavaEMFNature 31 | org.eclipse.wst.common.modulecore.ModuleCoreNature 32 | org.eclipse.jdt.core.javanature 33 | org.eclipse.m2e.core.maven2Nature 34 | org.eclipse.wst.common.project.facet.core.nature 35 | 36 | 37 | -------------------------------------------------------------------------------- /nredis-proxy-core/.settings/org.eclipse.core.resources.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | encoding//src/main/java=UTF-8 3 | encoding/=UTF-8 4 | -------------------------------------------------------------------------------- /nredis-proxy-core/.settings/org.eclipse.jdt.core.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled 3 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.7 4 | org.eclipse.jdt.core.compiler.compliance=1.7 5 | org.eclipse.jdt.core.compiler.problem.assertIdentifier=error 6 | org.eclipse.jdt.core.compiler.problem.enumIdentifier=error 7 | org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning 8 | org.eclipse.jdt.core.compiler.source=1.7 9 | -------------------------------------------------------------------------------- /nredis-proxy-core/.settings/org.eclipse.m2e.core.prefs: -------------------------------------------------------------------------------- 1 | activeProfiles= 2 | eclipse.preferences.version=1 3 | resolveWorkspaceProjects=true 4 | version=1 5 | -------------------------------------------------------------------------------- /nredis-proxy-core/.settings/org.eclipse.wst.common.component: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /nredis-proxy-core/.settings/org.eclipse.wst.common.project.facet.core.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /nredis-proxy-core/.settings/org.eclipse.wst.validation.prefs: -------------------------------------------------------------------------------- 1 | disabled=06target 2 | eclipse.preferences.version=1 3 | -------------------------------------------------------------------------------- /nredis-proxy-core/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.opensource 7 | nredis-proxy 8 | 1.0 9 | 10 | com.opensource 11 | nredis-proxy-core 12 | 1.0 13 | nredis-proxy-core 14 | http://maven.apache.org 15 | 16 | UTF-8 17 | 18 | 19 | 20 | junit 21 | junit 22 | test 23 | 24 | 25 | io.netty 26 | netty-all 27 | 28 | 29 | com.opensource 30 | nredis-proxy-commons 31 | 32 | 33 | com.opensource 34 | nredis-proxy-pool 35 | 36 | 37 | org.slf4j 38 | slf4j-api 39 | 40 | 41 | 42 | -------------------------------------------------------------------------------- /nredis-proxy-core/src/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wxmclub/nredis-proxy/4c5b599e4439e434ae10a7323f8ef2de5fc2b382/nredis-proxy-core/src/.DS_Store -------------------------------------------------------------------------------- /nredis-proxy-core/src/main/java/com/opensource/netty/redis/proxy/core/client/Client.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package com.opensource.netty.redis.proxy.core.client; 5 | 6 | /** 7 | * @author liubing 8 | * 9 | */ 10 | public interface Client { 11 | 12 | /** 13 | * open the channel 14 | * 15 | * @return 16 | */ 17 | boolean open(); 18 | 19 | /** 20 | * close the channel. 21 | */ 22 | void close(); 23 | 24 | /** 25 | * close the channel gracefully. 26 | */ 27 | void close(int timeout); 28 | 29 | /** 30 | * is closed. 31 | * 32 | * @return closed 33 | */ 34 | boolean isClosed(); 35 | 36 | /** 37 | * the node available status 38 | * 39 | * @return 40 | */ 41 | boolean isAvailable(); 42 | 43 | } 44 | -------------------------------------------------------------------------------- /nredis-proxy-core/src/main/java/com/opensource/netty/redis/proxy/core/client/impl/AbstractClient.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package com.opensource.netty.redis.proxy.core.client.impl; 5 | 6 | import com.opensource.netty.redis.proxy.core.client.Client; 7 | import com.opensource.netty.redis.proxy.core.enums.ChannelState; 8 | 9 | /** 10 | * @author liubing 11 | * 12 | */ 13 | public abstract class AbstractClient implements Client { 14 | 15 | protected volatile ChannelState state = ChannelState.UNINIT; 16 | } 17 | -------------------------------------------------------------------------------- /nredis-proxy-core/src/main/java/com/opensource/netty/redis/proxy/core/cluster/LoadBalance.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package com.opensource.netty.redis.proxy.core.cluster; 5 | 6 | import com.opensource.netty.redis.proxy.core.cluster.impl.support.RedisQuestBean; 7 | import com.opensource.netty.redis.proxy.core.config.LBRedisServerMasterCluster; 8 | import com.opensource.netty.redis.proxy.core.config.support.LBRedisServerBean; 9 | 10 | /** 11 | * 均衡轮询接口 12 | * @author liubing 13 | * 14 | */ 15 | public interface LoadBalance { 16 | 17 | /** 18 | * 刷新 19 | */ 20 | public void onRefresh(LBRedisServerMasterCluster ffanRedisServerMasterCluster); 21 | 22 | /** 23 | * 选取策略 24 | * @param redisQuestBean 25 | * @return 26 | */ 27 | public LBRedisServerBean select(RedisQuestBean redisQuestBean,LBRedisServerBean ffanRedisMasterServer ); 28 | 29 | /** 30 | * 设置 31 | * @param ffanRedisServerMasterCluster 32 | */ 33 | public void setFfanRedisServerMasterCluster(LBRedisServerMasterCluster ffanRedisServerMasterCluster); 34 | } 35 | -------------------------------------------------------------------------------- /nredis-proxy-core/src/main/java/com/opensource/netty/redis/proxy/core/cluster/impl/AbstractLoadBalance.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package com.opensource.netty.redis.proxy.core.cluster.impl; 5 | 6 | import java.util.List; 7 | 8 | import com.opensource.netty.redis.proxy.core.cluster.LoadBalance; 9 | import com.opensource.netty.redis.proxy.core.cluster.impl.support.RedisQuestBean; 10 | import com.opensource.netty.redis.proxy.core.config.LBRedisServerMasterCluster; 11 | import com.opensource.netty.redis.proxy.core.config.support.LBRedisServerBean; 12 | 13 | /** 14 | * @author liubing 15 | * 16 | */ 17 | public abstract class AbstractLoadBalance implements LoadBalance { 18 | 19 | 20 | 21 | private LBRedisServerMasterCluster ffanRedisServerMasterCluster; 22 | 23 | 24 | /** 25 | * @param ffanRedisServerMasterCluster 26 | */ 27 | public AbstractLoadBalance() { 28 | super(); 29 | } 30 | 31 | /* (non-Javadoc) 32 | * @see com.wanda.ffan.redis.proxy.core.cluster.LoadBalance#onRefresh(com.wanda.ffan.redis.proxy.core.config.FfanRedisServerMasterCluster) 33 | */ 34 | @Override 35 | public void onRefresh( 36 | LBRedisServerMasterCluster ffanRedisServerMasterCluster) { 37 | this.ffanRedisServerMasterCluster=ffanRedisServerMasterCluster; 38 | } 39 | 40 | /* (non-Javadoc) 41 | * @see com.wanda.ffan.redis.proxy.core.cluster.LoadBalance#select(com.wanda.ffan.redis.proxy.core.cluster.impl.support.RedisQuestBean) 42 | */ 43 | @Override 44 | public LBRedisServerBean select(RedisQuestBean redisQuestBean,LBRedisServerBean ffanRedisMasterServer) { 45 | if(redisQuestBean.isWrite()&&ffanRedisMasterServer==null){//写 46 | List ffanRedisServerBeans=ffanRedisServerMasterCluster.getMasters(); 47 | if(ffanRedisServerBeans.size()>1){//默认第一个 48 | LBRedisServerBean ffanRedisServerBean=doSelect(redisQuestBean,ffanRedisServerBeans); 49 | return ffanRedisServerBean; 50 | }else if(ffanRedisServerBeans.size()==1){ 51 | return ffanRedisServerBeans.get(0); 52 | } 53 | }else if(!redisQuestBean.isWrite()&&ffanRedisMasterServer!=null){//选取从 54 | List ffanRedisClusterServerBeans=ffanRedisServerMasterCluster.getMasterFfanRedisServerBean(ffanRedisMasterServer.getKey()); 55 | if(ffanRedisClusterServerBeans.size()>1){//默认第一个 56 | LBRedisServerBean ffanRedisServerBean=doSelect(redisQuestBean,ffanRedisClusterServerBeans); 57 | return ffanRedisServerBean; 58 | }else if(ffanRedisClusterServerBeans.size()==1){ 59 | return ffanRedisClusterServerBeans.get(0); 60 | } 61 | } 62 | return null; 63 | } 64 | 65 | /** 66 | * @return the ffanRedisServerMasterCluster 67 | */ 68 | public LBRedisServerMasterCluster getFfanRedisServerMasterCluster() { 69 | return ffanRedisServerMasterCluster; 70 | } 71 | 72 | /** 73 | * @param ffanRedisServerMasterCluster the ffanRedisServerMasterCluster to set 74 | */ 75 | public void setFfanRedisServerMasterCluster( 76 | LBRedisServerMasterCluster ffanRedisServerMasterCluster) { 77 | this.ffanRedisServerMasterCluster = ffanRedisServerMasterCluster; 78 | } 79 | 80 | /** 81 | * 选取策略 82 | * @param redisQuestBean 83 | * @return 84 | */ 85 | protected abstract LBRedisServerBean doSelect(RedisQuestBean redisQuestBean,List ffanRedisMasterServers); 86 | 87 | } 88 | -------------------------------------------------------------------------------- /nredis-proxy-core/src/main/java/com/opensource/netty/redis/proxy/core/cluster/impl/ConsistentHashLoadBalance.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package com.opensource.netty.redis.proxy.core.cluster.impl; 5 | 6 | import java.util.List; 7 | 8 | import com.opensource.netty.redis.proxy.commons.algorithm.Hashing; 9 | import com.opensource.netty.redis.proxy.commons.algorithm.impl.ConsistentHash; 10 | import com.opensource.netty.redis.proxy.commons.algorithm.impl.MurmurHash; 11 | import com.opensource.netty.redis.proxy.core.cluster.impl.support.RedisQuestBean; 12 | import com.opensource.netty.redis.proxy.core.config.support.LBRedisServerBean; 13 | 14 | /** 15 | * 一致性hash 16 | * @author liubing 17 | * 18 | */ 19 | public class ConsistentHashLoadBalance extends AbstractLoadBalance { 20 | 21 | 22 | public ConsistentHashLoadBalance() { 23 | 24 | } 25 | 26 | /* (non-Javadoc) 27 | * @see com.wanda.ffan.redis.proxy.core.cluster.impl.AbstractLoadBalance#doSelect(com.wanda.ffan.redis.proxy.core.cluster.impl.support.RedisQuestBean, java.util.List) 28 | */ 29 | @Override 30 | protected LBRedisServerBean doSelect(RedisQuestBean redisQuestBean, 31 | List ffanRedisMasterServers) { 32 | Hashing hashFunction = new MurmurHash(); // hash函数实例 33 | ConsistentHash consistentHash=new ConsistentHash(hashFunction, ffanRedisMasterServers.size(), ffanRedisMasterServers); 34 | LBRedisServerBean ffanRedisServerBean=consistentHash.getBytes(redisQuestBean.getKey()); 35 | return ffanRedisServerBean; 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /nredis-proxy-core/src/main/java/com/opensource/netty/redis/proxy/core/cluster/impl/RoundRobinLoadBalance.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package com.opensource.netty.redis.proxy.core.cluster.impl; 5 | 6 | import java.util.List; 7 | 8 | import com.opensource.netty.redis.proxy.commons.algorithm.impl.RoundRobinHash; 9 | import com.opensource.netty.redis.proxy.core.cluster.impl.support.RedisQuestBean; 10 | import com.opensource.netty.redis.proxy.core.config.support.LBRedisServerBean; 11 | 12 | /** 13 | * RoundRobin 权重算法 14 | * @author liubing 15 | * 16 | */ 17 | public class RoundRobinLoadBalance extends AbstractLoadBalance { 18 | 19 | public RoundRobinLoadBalance() { 20 | 21 | } 22 | 23 | /* (non-Javadoc) 24 | * @see com.wanda.ffan.redis.proxy.core.cluster.impl.AbstractLoadBalance#doSelect(com.wanda.ffan.redis.proxy.core.cluster.impl.support.RedisQuestBean, java.util.List) 25 | */ 26 | @Override 27 | protected LBRedisServerBean doSelect(RedisQuestBean redisQuestBean, 28 | List ffanRedisMasterServers) { 29 | RoundRobinHash roundRobinHash=new RoundRobinHash(ffanRedisMasterServers); 30 | LBRedisServerBean result=roundRobinHash.weightRandom(); 31 | return result; 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /nredis-proxy-core/src/main/java/com/opensource/netty/redis/proxy/core/cluster/impl/support/RedisQuestBean.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package com.opensource.netty.redis.proxy.core.cluster.impl.support; 5 | 6 | /** 7 | * redisproxy 接受请求中间类 8 | * @author liubing 9 | * 10 | */ 11 | public class RedisQuestBean { 12 | 13 | private String command;//命令 14 | 15 | private byte[] key;//关键字 16 | 17 | private boolean isWrite;//是否写 18 | 19 | /** 20 | * @param command 21 | * @param key 22 | * @param isWrite 23 | */ 24 | public RedisQuestBean(String command, byte[] key, boolean isWrite) { 25 | super(); 26 | this.command = command; 27 | this.key = key; 28 | this.isWrite = isWrite; 29 | } 30 | 31 | /** 32 | * @return the isWrite 33 | */ 34 | public boolean isWrite() { 35 | return isWrite; 36 | } 37 | 38 | 39 | 40 | /** 41 | * @param isWrite the isWrite to set 42 | */ 43 | public void setWrite(boolean isWrite) { 44 | this.isWrite = isWrite; 45 | } 46 | 47 | 48 | 49 | /** 50 | * 51 | */ 52 | public RedisQuestBean() { 53 | super(); 54 | } 55 | 56 | /** 57 | * @return the command 58 | */ 59 | public String getCommand() { 60 | return command; 61 | } 62 | 63 | /** 64 | * @param command the command to set 65 | */ 66 | public void setCommand(String command) { 67 | this.command = command; 68 | } 69 | 70 | /** 71 | * @return the key 72 | */ 73 | public byte[] getKey() { 74 | return key; 75 | } 76 | 77 | /** 78 | * @param key the key to set 79 | */ 80 | public void setKey(byte[] key) { 81 | this.key = key; 82 | } 83 | 84 | 85 | } 86 | -------------------------------------------------------------------------------- /nredis-proxy-core/src/main/java/com/opensource/netty/redis/proxy/core/command/IRedisCommand.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package com.opensource.netty.redis.proxy.core.command; 5 | 6 | import io.netty.buffer.ByteBuf; 7 | 8 | /** 9 | * @author liubing 10 | * 11 | */ 12 | public interface IRedisCommand { 13 | /** 14 | * 编码 15 | * @param byteBuf 16 | */ 17 | void encode(ByteBuf byteBuf); 18 | 19 | } 20 | -------------------------------------------------------------------------------- /nredis-proxy-core/src/main/java/com/opensource/netty/redis/proxy/core/command/impl/RedisCommand.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package com.opensource.netty.redis.proxy.core.command.impl; 5 | 6 | import java.util.List; 7 | 8 | import io.netty.buffer.ByteBuf; 9 | 10 | import com.opensource.netty.redis.proxy.commons.constants.RedisConstants; 11 | import com.opensource.netty.redis.proxy.commons.utils.ProtoUtils; 12 | import com.opensource.netty.redis.proxy.core.command.IRedisCommand; 13 | 14 | /** 15 | * @author liubing 16 | * 17 | */ 18 | public class RedisCommand implements IRedisCommand { 19 | 20 | private int argCount; 21 | private List args; 22 | 23 | private Long requestKey; 24 | /* 25 | * (non-Javadoc) 26 | * 27 | * @see 28 | * com.wanda.ffan.redis.proxy.core.command.IRedisCommand#encode(io.netty 29 | * .buffer.ByteBuf) 30 | */ 31 | @Override 32 | public void encode(ByteBuf byteBuf) { 33 | byteBuf.writeByte((byte) RedisConstants.ASTERISK_BYTE); 34 | byteBuf.writeBytes(ProtoUtils.convertIntToByteArray(args.size())); 35 | writeCRLF(byteBuf); 36 | for (byte[] arg : args) { 37 | byteBuf.writeByte((byte) RedisConstants.DOLLAR_BYTE); 38 | byteBuf.writeBytes(ProtoUtils.convertIntToByteArray(arg.length)); 39 | writeCRLF(byteBuf); 40 | byteBuf.writeBytes(arg); 41 | writeCRLF(byteBuf); 42 | } 43 | } 44 | 45 | /** 46 | * @return the argCount 47 | */ 48 | public int getArgCount() { 49 | return argCount; 50 | } 51 | 52 | /** 53 | * @param argCount 54 | * the argCount to set 55 | */ 56 | public void setArgCount(int argCount) { 57 | this.argCount = argCount; 58 | } 59 | 60 | /** 61 | * @return the args 62 | */ 63 | public List getArgs() { 64 | return args; 65 | } 66 | 67 | /** 68 | * @param args 69 | * the args to set 70 | */ 71 | public void setArgs(List args) { 72 | this.args = args; 73 | } 74 | 75 | 76 | private void writeCRLF(ByteBuf byteBuf) { 77 | byteBuf.writeByte(RedisConstants.CR_BYTE); 78 | byteBuf.writeByte(RedisConstants.LF_BYTE); 79 | } 80 | 81 | /** 82 | * @return the requestKey 83 | */ 84 | public Long getRequestKey() { 85 | return requestKey; 86 | } 87 | 88 | /** 89 | * @param requestKey the requestKey to set 90 | */ 91 | public void setRequestKey(Long requestKey) { 92 | this.requestKey = requestKey; 93 | } 94 | 95 | 96 | } 97 | -------------------------------------------------------------------------------- /nredis-proxy-core/src/main/java/com/opensource/netty/redis/proxy/core/command/impl/ShutdownCommand.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package com.opensource.netty.redis.proxy.core.command.impl; 5 | 6 | import io.netty.buffer.ByteBuf; 7 | 8 | import com.opensource.netty.redis.proxy.core.command.IRedisCommand; 9 | 10 | /** 11 | * @author liubing 12 | * 13 | */ 14 | public class ShutdownCommand implements IRedisCommand { 15 | 16 | /* (non-Javadoc) 17 | * @see com.wanda.ffan.redis.proxy.core.command.IRedisCommand#encode(io.netty.buffer.ByteBuf) 18 | */ 19 | @Override 20 | public void encode(ByteBuf byteBuf) { 21 | // TODO Auto-generated method stub 22 | 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /nredis-proxy-core/src/main/java/com/opensource/netty/redis/proxy/core/config/support/LBRedisServerClusterBean.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package com.opensource.netty.redis.proxy.core.config.support; 5 | 6 | import java.util.List; 7 | 8 | import com.opensource.netty.redis.proxy.core.cluster.LoadBalance; 9 | 10 | /** 11 | * 一主多从 12 | * @author liubing 13 | * 14 | */ 15 | public class LBRedisServerClusterBean { 16 | 17 | private LBRedisServerBean ffanMasterRedisServerBean;//主 18 | 19 | private List ffanRedisServerClusterBeans;//从 20 | 21 | private LoadBalance loadClusterBalance;//从权重 22 | /** 23 | * 24 | */ 25 | public LBRedisServerClusterBean() { 26 | super(); 27 | } 28 | 29 | /** 30 | * @return the ffanMasterRedisServerBean 31 | */ 32 | public LBRedisServerBean getFfanMasterRedisServerBean() { 33 | return ffanMasterRedisServerBean; 34 | } 35 | 36 | /** 37 | * @param ffanMasterRedisServerBean the ffanMasterRedisServerBean to set 38 | */ 39 | public void setFfanMasterRedisServerBean( 40 | LBRedisServerBean ffanMasterRedisServerBean) { 41 | this.ffanMasterRedisServerBean = ffanMasterRedisServerBean; 42 | } 43 | 44 | /** 45 | * @return the ffanRedisServerClusterBeans 46 | */ 47 | public List getFfanRedisServerClusterBeans() { 48 | return ffanRedisServerClusterBeans; 49 | } 50 | 51 | /** 52 | * @param ffanRedisServerClusterBeans the ffanRedisServerClusterBeans to set 53 | */ 54 | public void setFfanRedisServerClusterBeans( 55 | List ffanRedisServerClusterBeans) { 56 | this.ffanRedisServerClusterBeans = ffanRedisServerClusterBeans; 57 | } 58 | 59 | /** 60 | * @return the loadClusterBalance 61 | */ 62 | public LoadBalance getLoadClusterBalance() { 63 | return loadClusterBalance; 64 | } 65 | 66 | /** 67 | * @param loadClusterBalance the loadClusterBalance to set 68 | */ 69 | public void setLoadClusterBalance(LoadBalance loadClusterBalance) { 70 | this.loadClusterBalance = loadClusterBalance; 71 | } 72 | 73 | 74 | 75 | } 76 | -------------------------------------------------------------------------------- /nredis-proxy-core/src/main/java/com/opensource/netty/redis/proxy/core/connection/IConnection.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package com.opensource.netty.redis.proxy.core.connection; 5 | 6 | import com.opensource.netty.redis.proxy.core.command.impl.RedisCommand; 7 | import com.opensource.netty.redis.proxy.pool.commons.Pool; 8 | 9 | /** 10 | * @author liubing 11 | * 12 | */ 13 | public interface IConnection extends Pool{ 14 | 15 | public void write(RedisCommand request,IConnectionCallBack connectionCallBack); 16 | 17 | /** 18 | * open the channel 19 | * 20 | * @return 21 | */ 22 | boolean open(); 23 | 24 | /** 25 | * close the channel. 26 | */ 27 | void close(); 28 | 29 | /** 30 | * close the channel gracefully. 31 | */ 32 | void close(int timeout); 33 | 34 | /** 35 | * is closed. 36 | * 37 | * @return closed 38 | */ 39 | boolean isClosed(); 40 | 41 | /** 42 | * the node available status 43 | * 44 | * @return 45 | */ 46 | boolean isAvailable(); 47 | } 48 | -------------------------------------------------------------------------------- /nredis-proxy-core/src/main/java/com/opensource/netty/redis/proxy/core/connection/IConnectionCallBack.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package com.opensource.netty.redis.proxy.core.connection; 5 | 6 | import com.opensource.netty.redis.proxy.core.reply.IRedisReply; 7 | 8 | /** 9 | * redis 连接回答回调方法 10 | * @author liubing 11 | * 12 | */ 13 | public interface IConnectionCallBack { 14 | 15 | /** 16 | * 处理回答 17 | * @param reply 18 | */ 19 | void handleReply(IRedisReply reply); 20 | } 21 | -------------------------------------------------------------------------------- /nredis-proxy-core/src/main/java/com/opensource/netty/redis/proxy/core/connection/impl/RedisConnectionCallBack.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package com.opensource.netty.redis.proxy.core.connection.impl; 5 | 6 | import io.netty.channel.Channel; 7 | 8 | import com.opensource.netty.redis.proxy.core.connection.IConnectionCallBack; 9 | import com.opensource.netty.redis.proxy.core.reply.IRedisReply; 10 | 11 | /** 12 | * 13 | * @author liubing 14 | * 15 | */ 16 | public class RedisConnectionCallBack implements IConnectionCallBack { 17 | 18 | private Channel channel; 19 | /* (non-Javadoc) 20 | * @see com.wanda.ffan.redis.proxy.core.connection.IConnectionCallBack#handleReply(com.wanda.ffan.redis.proxy.core.reply.IRedisReply) 21 | */ 22 | @Override 23 | public void handleReply(IRedisReply reply) { 24 | channel.writeAndFlush(reply); 25 | } 26 | /** 27 | * @param channel 28 | */ 29 | public RedisConnectionCallBack(Channel channel) { 30 | super(); 31 | this.channel = channel; 32 | } 33 | 34 | 35 | } 36 | -------------------------------------------------------------------------------- /nredis-proxy-core/src/main/java/com/opensource/netty/redis/proxy/core/enums/ChannelState.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package com.opensource.netty.redis.proxy.core.enums; 5 | 6 | /** 7 | * channel 节点的状态 8 | * @author liubing 9 | * 10 | */ 11 | public enum ChannelState { 12 | 13 | /** 未初始化状态 **/ 14 | UNINIT(0), 15 | /** 初始化完成 **/ 16 | INIT(1), 17 | /** 存活可用状态 **/ 18 | ALIVE(2), 19 | /** 不存活可用状态 **/ 20 | UNALIVE(3), 21 | /** 关闭状态 **/ 22 | CLOSE(4); 23 | 24 | public final int value; 25 | 26 | private ChannelState(int value) { 27 | this.value = value; 28 | } 29 | 30 | public boolean isAliveState() { 31 | return this == ALIVE; 32 | } 33 | 34 | public boolean isUnAliveState() { 35 | return this == UNALIVE; 36 | } 37 | 38 | public boolean isCloseState() { 39 | return this == CLOSE; 40 | } 41 | 42 | public boolean isInitState() { 43 | return this == INIT; 44 | } 45 | 46 | public boolean isUnInitState() { 47 | return this == UNINIT; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /nredis-proxy-core/src/main/java/com/opensource/netty/redis/proxy/core/enums/RedisProxyParamType.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package com.opensource.netty.redis.proxy.core.enums; 5 | 6 | import com.opensource.netty.redis.proxy.commons.constants.RedisConstants; 7 | 8 | /** 9 | * @author liubing 10 | * 11 | */ 12 | public enum RedisProxyParamType { 13 | 14 | /** request timeout **/ 15 | requestTimeout("requestTimeout", 200), 16 | /** request id from http interface **/ 17 | requestIdFromClient("requestIdFromClient", 0), 18 | /** connect timeout **/ 19 | connectTimeout("connectTimeout", 1000), 20 | /** service min worker threads **/ 21 | minWorkerThread("minWorkerThread", 20), 22 | /** service max worker threads **/ 23 | maxWorkerThread("maxWorkerThread", 200), 24 | /** pool min conn number **/ 25 | minClientConnection("minClientConnection", 2), 26 | /** pool max conn number **/ 27 | maxClientConnection("maxClientConnection", 50), 28 | /** pool max conn number **/ 29 | maxContentLength("maxContentLength", 10 * 1024 * 1024), 30 | /** max server conn (all clients conn) **/ 31 | maxServerConnection("maxServerConnection", 100000), 32 | /** pool conn manger stragy **/ 33 | poolLifo("poolLifo", true), 34 | check("check", "true"), 35 | registryRetryPeriod("registryRetryPeriod", 30 * RedisConstants.SECOND_MILLS), 36 | registrySessionTimeout("registrySessionTimeout", 1 * RedisConstants.MINUTE_MILLS), 37 | 38 | 39 | /** multi referer share the same channel **/ 40 | shareChannel("shareChannel", false), 41 | REDISSERVER("REDISSERVER", "{}"); 42 | 43 | private String name; 44 | private String value; 45 | private long longValue; 46 | private int intValue; 47 | private boolean boolValue; 48 | 49 | private RedisProxyParamType(String name, String value) { 50 | this.name = name; 51 | this.value = value; 52 | } 53 | 54 | private RedisProxyParamType(String name, long longValue) { 55 | this.name = name; 56 | this.value = String.valueOf(longValue); 57 | this.longValue = longValue; 58 | } 59 | 60 | private RedisProxyParamType(String name, int intValue) { 61 | this.name = name; 62 | this.value = String.valueOf(intValue); 63 | this.intValue = intValue; 64 | } 65 | 66 | private RedisProxyParamType(String name, boolean boolValue) { 67 | this.name = name; 68 | this.value = String.valueOf(boolValue); 69 | this.boolValue = boolValue; 70 | } 71 | 72 | public String getName() { 73 | return name; 74 | } 75 | 76 | public String getValue() { 77 | return value; 78 | } 79 | 80 | public int getIntValue() { 81 | return intValue; 82 | } 83 | 84 | public long getLongValue() { 85 | return longValue; 86 | } 87 | 88 | public boolean getBooleanValue() { 89 | return boolValue; 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /nredis-proxy-core/src/main/java/com/opensource/netty/redis/proxy/core/enums/ReplyState.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package com.opensource.netty.redis.proxy.core.enums; 5 | 6 | /** 7 | * 状态枚举类 8 | * @author liubing 9 | * 10 | */ 11 | public enum ReplyState { 12 | READ_INIT, 13 | READ_REPLY 14 | } 15 | -------------------------------------------------------------------------------- /nredis-proxy-core/src/main/java/com/opensource/netty/redis/proxy/core/enums/RequestState.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package com.opensource.netty.redis.proxy.core.enums; 5 | 6 | /** 7 | * @author liubing 8 | * 9 | */ 10 | public enum RequestState { 11 | READ_SKIP,//健壮性考虑,如果第一个字符不是*则skip直到遇到* 12 | READ_INIT, 13 | READ_ARGC,//参数数量 14 | READ_ARG, //参数 15 | READ_END 16 | } 17 | -------------------------------------------------------------------------------- /nredis-proxy-core/src/main/java/com/opensource/netty/redis/proxy/core/enums/Type.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package com.opensource.netty.redis.proxy.core.enums; 5 | 6 | /** 7 | * 类型枚举类 8 | * @author liubing 9 | * 10 | */ 11 | public enum Type { 12 | 13 | ERROR((byte) '-'), 14 | STATUS((byte) '+'), 15 | BULK((byte) '$'), 16 | INTEGER((byte) ':'), 17 | MULTYBULK((byte) '*'),; 18 | 19 | private byte code; 20 | 21 | Type(byte code) { 22 | this.code = code; 23 | } 24 | 25 | public byte getCode() { 26 | return this.code; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /nredis-proxy-core/src/main/java/com/opensource/netty/redis/proxy/core/enums/ZkNodeType.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package com.opensource.netty.redis.proxy.core.enums; 5 | 6 | /** 7 | * @author liubing 8 | * 9 | */ 10 | public enum ZkNodeType { 11 | 12 | AVAILABLE_SERVER, 13 | UNAVAILABLE_SERVER, 14 | CLIENT 15 | } 16 | -------------------------------------------------------------------------------- /nredis-proxy-core/src/main/java/com/opensource/netty/redis/proxy/core/listen/IRegistryListen.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package com.opensource.netty.redis.proxy.core.listen; 5 | 6 | import java.util.List; 7 | 8 | /** 9 | * @author liubing 10 | * 11 | */ 12 | public interface IRegistryListen { 13 | 14 | /** 15 | * 监听处理数据变化 16 | * @param dataPath 17 | * @param data 18 | */ 19 | public void handleDataChange(String dataPath, Object data); 20 | 21 | /** 22 | * 处理子节点变化 23 | * 更新从权重的变化 24 | * @param parentPath 25 | * @param currentChilds 26 | */ 27 | public void handleChildChange(String data,String path, List ChildDatas); 28 | 29 | /** 30 | * 数据节点删除 31 | * @param dataPath 32 | */ 33 | public void handleDataDeleted(String dataPath); 34 | } 35 | -------------------------------------------------------------------------------- /nredis-proxy-core/src/main/java/com/opensource/netty/redis/proxy/core/listen/impl/AbstractRegistryListenImpl.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package com.opensource.netty.redis.proxy.core.listen.impl; 5 | 6 | 7 | import com.opensource.netty.redis.proxy.core.config.LBRedisServerMasterCluster; 8 | import com.opensource.netty.redis.proxy.core.listen.IRegistryListen; 9 | 10 | /** 11 | * @author liubing 12 | * 13 | */ 14 | public abstract class AbstractRegistryListenImpl implements IRegistryListen { 15 | 16 | private LBRedisServerMasterCluster ffanRedisServerMasterCluster; 17 | 18 | 19 | /** 20 | * @param ffanRedisServerMasterCluster 21 | */ 22 | public AbstractRegistryListenImpl( 23 | LBRedisServerMasterCluster ffanRedisServerMasterCluster) { 24 | super(); 25 | this.ffanRedisServerMasterCluster = ffanRedisServerMasterCluster; 26 | } 27 | 28 | 29 | /** 30 | * @return the ffanRedisServerMasterCluster 31 | */ 32 | public LBRedisServerMasterCluster getFfanRedisServerMasterCluster() { 33 | return ffanRedisServerMasterCluster; 34 | } 35 | 36 | 37 | /** 38 | * @param ffanRedisServerMasterCluster the ffanRedisServerMasterCluster to set 39 | */ 40 | public void setFfanRedisServerMasterCluster( 41 | LBRedisServerMasterCluster ffanRedisServerMasterCluster) { 42 | this.ffanRedisServerMasterCluster = ffanRedisServerMasterCluster; 43 | } 44 | 45 | 46 | 47 | } 48 | -------------------------------------------------------------------------------- /nredis-proxy-core/src/main/java/com/opensource/netty/redis/proxy/core/log/ILogService.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package com.opensource.netty.redis.proxy.core.log; 5 | 6 | /** 7 | * log服务。方便适配不同的log方式和配置 8 | * @author liubing 9 | * 10 | */ 11 | public interface ILogService { 12 | 13 | void trace(String msg); 14 | 15 | void trace(String format, Object... argArray); 16 | 17 | void debug(String msg); 18 | 19 | void debug(String format, Object... argArray); 20 | 21 | void debug(String msg, Throwable t); 22 | 23 | void info(String msg); 24 | 25 | void info(String format, Object... argArray); 26 | 27 | void info(String msg, Throwable t); 28 | 29 | void warn(String msg); 30 | 31 | void warn(String format, Object... argArray); 32 | 33 | void warn(String msg, Throwable t); 34 | 35 | void error(String msg); 36 | 37 | void error(String format, Object... argArray); 38 | 39 | void error(String msg, Throwable t); 40 | 41 | void accessLog(String msg); 42 | 43 | void accessProfileLog(String format, Object... argArray); 44 | 45 | void accessStatsLog(String msg); 46 | 47 | void accessStatsLog(String format, Object... argArray); 48 | 49 | boolean isTraceEnabled(); 50 | 51 | boolean isDebugEnabled(); 52 | 53 | boolean isWarnEnabled(); 54 | 55 | boolean isErrorEnabled(); 56 | 57 | boolean isStatsEnabled(); 58 | } 59 | -------------------------------------------------------------------------------- /nredis-proxy-core/src/main/java/com/opensource/netty/redis/proxy/core/log/impl/LogService.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package com.opensource.netty.redis.proxy.core.log.impl; 5 | 6 | import org.slf4j.Logger; 7 | import org.slf4j.LoggerFactory; 8 | 9 | import com.opensource.netty.redis.proxy.core.log.ILogService; 10 | /** 11 | * @author liubing 12 | * 13 | */ 14 | public class LogService implements ILogService { 15 | 16 | private static Logger trace = LoggerFactory.getLogger("trace"); 17 | private static Logger debug = LoggerFactory.getLogger("debug"); 18 | private static Logger info = LoggerFactory.getLogger("info"); 19 | private static Logger warn = LoggerFactory.getLogger("warn"); 20 | private static Logger error = LoggerFactory.getLogger("error"); 21 | private static Logger access = LoggerFactory.getLogger("accessLog"); 22 | private static Logger serviceStats = LoggerFactory 23 | .getLogger("serviceStatsLog"); 24 | private static Logger profileLogger = LoggerFactory.getLogger("profile"); 25 | 26 | public void trace(String msg) { 27 | trace.trace(msg); 28 | } 29 | 30 | @Override 31 | public void trace(String format, Object... argArray) { 32 | trace.trace(format, argArray); 33 | } 34 | 35 | public void debug(String msg) { 36 | debug.debug(msg); 37 | } 38 | 39 | public void debug(String format, Object... argArray) { 40 | debug.debug(format, argArray); 41 | } 42 | 43 | public void debug(String msg, Throwable t) { 44 | debug.debug(msg, t); 45 | } 46 | 47 | public void info(String msg) { 48 | info.info(msg); 49 | } 50 | 51 | public void info(String format, Object... argArray) { 52 | info.info(format, argArray); 53 | } 54 | 55 | public void info(String msg, Throwable t) { 56 | info.info(msg, t); 57 | } 58 | 59 | public void warn(String msg) { 60 | warn.warn(msg); 61 | } 62 | 63 | public void warn(String format, Object... argArray) { 64 | warn.warn(format, argArray); 65 | } 66 | 67 | public void warn(String msg, Throwable t) { 68 | warn.warn(msg, t); 69 | } 70 | 71 | public void error(String msg) { 72 | error.error(msg); 73 | } 74 | 75 | public void error(String format, Object... argArray) { 76 | error.error(format, argArray); 77 | } 78 | 79 | public void error(String msg, Throwable t) { 80 | error.error(msg, t); 81 | } 82 | 83 | public void accessLog(String msg) { 84 | access.info(msg); 85 | } 86 | 87 | public void accessStatsLog(String msg) { 88 | serviceStats.info(msg); 89 | } 90 | 91 | public void accessStatsLog(String format, Object... argArray) { 92 | serviceStats.info(format, argArray); 93 | } 94 | 95 | public void accessProfileLog(String format, Object... argArray) { 96 | profileLogger.info(format, argArray); 97 | } 98 | 99 | @Override 100 | public boolean isTraceEnabled() { 101 | return trace.isTraceEnabled(); 102 | } 103 | 104 | @Override 105 | public boolean isDebugEnabled() { 106 | return debug.isDebugEnabled(); 107 | } 108 | 109 | @Override 110 | public boolean isWarnEnabled() { 111 | return warn.isWarnEnabled(); 112 | } 113 | 114 | @Override 115 | public boolean isErrorEnabled() { 116 | return error.isErrorEnabled(); 117 | } 118 | 119 | @Override 120 | public boolean isStatsEnabled() { 121 | return serviceStats.isInfoEnabled(); 122 | } 123 | 124 | } 125 | -------------------------------------------------------------------------------- /nredis-proxy-core/src/main/java/com/opensource/netty/redis/proxy/core/log/impl/LoggerUtils.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package com.opensource.netty.redis.proxy.core.log.impl; 5 | 6 | import com.opensource.netty.redis.proxy.core.log.ILogService; 7 | /** 8 | * @author liubing 9 | * 10 | */ 11 | public class LoggerUtils { 12 | 13 | private static ILogService logService = new LogService(); 14 | 15 | public static boolean isTraceEnabled() { 16 | return logService.isTraceEnabled(); 17 | } 18 | 19 | public static boolean isDebugEnabled() { 20 | return logService.isDebugEnabled(); 21 | } 22 | 23 | public static boolean isWarnEnabled() { 24 | return logService.isWarnEnabled(); 25 | } 26 | 27 | public static boolean isErrorEnabled() { 28 | return logService.isErrorEnabled(); 29 | } 30 | 31 | public static boolean isStatsEnabled() { 32 | return logService.isStatsEnabled(); 33 | } 34 | 35 | public static void trace(String msg) { 36 | logService.trace(msg); 37 | } 38 | 39 | public static void debug(String msg) { 40 | logService.debug(msg); 41 | } 42 | 43 | public static void debug(String format, Object... argArray) { 44 | logService.debug(format, argArray); 45 | } 46 | 47 | public static void debug(String msg, Throwable t) { 48 | logService.debug(msg, t); 49 | } 50 | 51 | public static void info(String msg) { 52 | logService.info(msg); 53 | } 54 | 55 | public static void info(String format, Object... argArray) { 56 | logService.info(format, argArray); 57 | } 58 | 59 | public static void info(String msg, Throwable t) { 60 | logService.info(msg, t); 61 | } 62 | 63 | public static void warn(String msg) { 64 | logService.warn(msg); 65 | } 66 | 67 | public static void warn(String format, Object... argArray) { 68 | logService.warn(format, argArray); 69 | } 70 | 71 | public static void warn(String msg, Throwable t) { 72 | logService.warn(msg, t); 73 | } 74 | 75 | public static void error(String msg) { 76 | logService.error(msg); 77 | } 78 | 79 | public static void error(String format, Object... argArray) { 80 | logService.error(format, argArray); 81 | } 82 | 83 | public static void error(String msg, Throwable t) { 84 | logService.error(msg, t); 85 | } 86 | 87 | public static void accessLog(String msg) { 88 | logService.accessLog(msg); 89 | } 90 | 91 | public static void accessStatsLog(String msg) { 92 | logService.accessStatsLog(msg); 93 | } 94 | 95 | public static void accessStatsLog(String format, Object... argArray) { 96 | logService.accessStatsLog(format, argArray); 97 | } 98 | 99 | public static void accessProfileLog(String format, Object... argArray) { 100 | logService.accessProfileLog(format, argArray); 101 | } 102 | 103 | public static ILogService getLogService() { 104 | return logService; 105 | } 106 | 107 | public static void setLogService(ILogService logService) { 108 | LoggerUtils.logService = logService; 109 | } 110 | } 111 | -------------------------------------------------------------------------------- /nredis-proxy-core/src/main/java/com/opensource/netty/redis/proxy/core/pool/utils/LBRedisProxyChannelPoolUtils.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package com.opensource.netty.redis.proxy.core.pool.utils; 5 | 6 | import com.opensource.netty.redis.proxy.core.connection.IConnection; 7 | import com.opensource.netty.redis.proxy.pool.LBRedisProxyIdleEntriesQueue; 8 | import com.opensource.netty.redis.proxy.pool.LBRedisProxyPoolEntryFactory; 9 | import com.opensource.netty.redis.proxy.pool.LBRedisProxyPooledObjectFactory; 10 | import com.opensource.netty.redis.proxy.pool.commons.LBRedisProxyPoolConfig; 11 | import com.opensource.netty.redis.proxy.pool.impl.LBRedisProxyBasicPool; 12 | import com.opensource.netty.redis.proxy.pool.impl.LBRedisProxyPoolBasicEntryFactory; 13 | import com.opensource.netty.redis.proxy.pool.impl.LBRedisProxyPoolBasicIdleEntriesQueue; 14 | 15 | 16 | 17 | /** 18 | * @author liubing 19 | * 20 | */ 21 | public class LBRedisProxyChannelPoolUtils { 22 | 23 | public static LBRedisProxyBasicPool createPool(LBRedisProxyPoolConfig config, LBRedisProxyPooledObjectFactory factory) throws Exception { 24 | return createPool( config, createQueue(config),createPoolEntryFactory(factory)); 25 | } 26 | 27 | private static LBRedisProxyPoolEntryFactory createPoolEntryFactory(LBRedisProxyPooledObjectFactory objectFactory) { 28 | 29 | return new LBRedisProxyPoolBasicEntryFactory(objectFactory); 30 | } 31 | 32 | private static LBRedisProxyIdleEntriesQueue createQueue( LBRedisProxyPoolConfig config) { 33 | return new LBRedisProxyPoolBasicIdleEntriesQueue(config); 34 | } 35 | 36 | 37 | public static LBRedisProxyBasicPool createPool(LBRedisProxyPoolConfig config, LBRedisProxyIdleEntriesQueue queue, LBRedisProxyPoolEntryFactory factory) throws Exception { 38 | return new LBRedisProxyBasicPool(config, queue, factory); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /nredis-proxy-core/src/main/java/com/opensource/netty/redis/proxy/core/protocol/RedisReplyEncoder.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package com.opensource.netty.redis.proxy.core.protocol; 5 | 6 | import com.opensource.netty.redis.proxy.core.reply.IRedisReply; 7 | 8 | import io.netty.buffer.ByteBuf; 9 | import io.netty.channel.ChannelHandlerContext; 10 | import io.netty.handler.codec.MessageToByteEncoder; 11 | 12 | /** 13 | * @author liubing 14 | * 15 | */ 16 | public class RedisReplyEncoder extends MessageToByteEncoder { 17 | 18 | @Override 19 | protected void encode(ChannelHandlerContext ctx, IRedisReply msg, 20 | ByteBuf out) throws Exception { 21 | msg.encode(out); 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /nredis-proxy-core/src/main/java/com/opensource/netty/redis/proxy/core/protocol/RedisRequestEncoder.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package com.opensource.netty.redis.proxy.core.protocol; 5 | 6 | import com.opensource.netty.redis.proxy.core.command.impl.RedisCommand; 7 | 8 | import io.netty.buffer.ByteBuf; 9 | import io.netty.channel.ChannelHandlerContext; 10 | import io.netty.handler.codec.MessageToByteEncoder; 11 | 12 | /** 13 | * request编码 14 | * @author liubing 15 | * 16 | */ 17 | public class RedisRequestEncoder extends MessageToByteEncoder { 18 | 19 | @Override 20 | protected void encode(ChannelHandlerContext ctx, RedisCommand msg, 21 | ByteBuf out) throws Exception { 22 | msg.encode(out); 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /nredis-proxy-core/src/main/java/com/opensource/netty/redis/proxy/core/registry/NotifyListener.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package com.opensource.netty.redis.proxy.core.registry; 5 | 6 | import java.util.List; 7 | 8 | import com.opensource.netty.redis.proxy.core.url.RedisProxyURL; 9 | 10 | /** 11 | * @author liubing 12 | * 13 | */ 14 | public interface NotifyListener { 15 | 16 | /** 17 | * 提醒 18 | * @param redisProxyURL 19 | * @param redisProxyURLClusters 20 | */ 21 | void notify(RedisProxyURL redisProxyURL,List redisProxyURLClusters); 22 | } 23 | -------------------------------------------------------------------------------- /nredis-proxy-core/src/main/java/com/opensource/netty/redis/proxy/core/registry/Registry.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package com.opensource.netty.redis.proxy.core.registry; 5 | 6 | import com.opensource.netty.redis.proxy.core.url.RedisProxyURL; 7 | 8 | /** 9 | * @author liubing 10 | * 11 | */ 12 | public interface Registry extends RegistryService { 13 | 14 | /** 15 | * 获取返回值 16 | * @return 17 | */ 18 | RedisProxyURL getRedisProxyURL(); 19 | } 20 | -------------------------------------------------------------------------------- /nredis-proxy-core/src/main/java/com/opensource/netty/redis/proxy/core/registry/RegistryFactory.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package com.opensource.netty.redis.proxy.core.registry; 5 | 6 | import com.opensource.netty.redis.proxy.core.url.RedisProxyURL; 7 | 8 | 9 | /** 10 | * @author liubing 11 | * 12 | */ 13 | public interface RegistryFactory { 14 | 15 | /** 16 | * 17 | * @param redisProxyURL 18 | * @return 19 | */ 20 | Registry getRegistry(RedisProxyURL redisProxyURL); 21 | } 22 | -------------------------------------------------------------------------------- /nredis-proxy-core/src/main/java/com/opensource/netty/redis/proxy/core/registry/RegistryService.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package com.opensource.netty.redis.proxy.core.registry; 5 | 6 | import java.util.List; 7 | 8 | import com.opensource.netty.redis.proxy.core.listen.IRegistryListen; 9 | import com.opensource.netty.redis.proxy.core.url.RedisProxyURL; 10 | 11 | /** 12 | * @author liubing 13 | * 14 | */ 15 | public interface RegistryService { 16 | 17 | /** 18 | * 注册监听值的变化 master节点 19 | * @param redisProxyURL 20 | */ 21 | void register(RedisProxyURL redisProxyURL,IRegistryListen registryListen); 22 | 23 | /** 24 | * 不注册监听值的变化 master 节点 25 | * 26 | * @param redisProxyURL 27 | */ 28 | void unregister(RedisProxyURL redisProxyURL); 29 | 30 | /** 31 | * 创建一个节点 cluster节点 32 | * @param redisProxyURL 33 | * @param parentPath 34 | * @param value 35 | */ 36 | void createPersistent(RedisProxyURL redisProxyURL,String value); 37 | 38 | /** 39 | * 删除节点 40 | * @param redisProxyURL 41 | * @param parentPath 42 | * @return 43 | */ 44 | boolean delete(RedisProxyURL redisProxyURL,String parentPath); 45 | 46 | /** 47 | * 获取子段路径 48 | * @param parentPath 49 | * @return 50 | */ 51 | public List getChildren(String parentPath); 52 | 53 | /** 54 | * 55 | * @param path 56 | * @param flag 57 | * @return 58 | */ 59 | public String readData(String path,boolean flag); 60 | } 61 | -------------------------------------------------------------------------------- /nredis-proxy-core/src/main/java/com/opensource/netty/redis/proxy/core/registry/impl/AbstractRegistryFactory.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package com.opensource.netty.redis.proxy.core.registry.impl; 5 | 6 | import java.util.concurrent.ConcurrentHashMap; 7 | import java.util.concurrent.locks.ReentrantLock; 8 | 9 | import com.opensource.netty.redis.proxy.commons.constants.LBRedisProxyErrorMsgConstant; 10 | import com.opensource.netty.redis.proxy.commons.exception.LBRedisProxyFrameworkException; 11 | import com.opensource.netty.redis.proxy.core.registry.Registry; 12 | import com.opensource.netty.redis.proxy.core.registry.RegistryFactory; 13 | import com.opensource.netty.redis.proxy.core.url.RedisProxyURL; 14 | 15 | /** 16 | * @author liubing 17 | * 18 | */ 19 | public abstract class AbstractRegistryFactory implements RegistryFactory { 20 | 21 | private static ConcurrentHashMap registries = new ConcurrentHashMap(); 22 | 23 | private static final ReentrantLock lock = new ReentrantLock(); 24 | 25 | protected String getRegistryUri(RedisProxyURL url) { 26 | String registryUri = url.getServerKey(); 27 | return registryUri; 28 | } 29 | 30 | /* (non-Javadoc) 31 | * @see com.wanda.ffan.redis.proxy.core.registry.RegistryFactory#getRegistry(com.wanda.ffan.redis.proxy.core.url.RedisProxyURL) 32 | */ 33 | @Override 34 | public Registry getRegistry(RedisProxyURL redisProxyURL) { 35 | String registryUri = getRegistryUri(redisProxyURL); 36 | try { 37 | lock.lock(); 38 | Registry registry = registries.get(registryUri); 39 | if (registry != null) { 40 | return registry; 41 | } 42 | registry = createRegistry(redisProxyURL); 43 | if (registry == null) { 44 | throw new LBRedisProxyFrameworkException("Create registry false for url:" + registryUri, LBRedisProxyErrorMsgConstant.FRAMEWORK_INIT_ERROR); 45 | } 46 | registries.put(registryUri, registry); 47 | return registry; 48 | } catch (Exception e) { 49 | throw new LBRedisProxyFrameworkException("Create registry false for url:" + registryUri, e, LBRedisProxyErrorMsgConstant.FRAMEWORK_INIT_ERROR); 50 | } finally { 51 | lock.unlock(); 52 | } 53 | } 54 | 55 | protected abstract Registry createRegistry(RedisProxyURL url); 56 | } 57 | -------------------------------------------------------------------------------- /nredis-proxy-core/src/main/java/com/opensource/netty/redis/proxy/core/registry/impl/support/ZkUtils.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package com.opensource.netty.redis.proxy.core.registry.impl.support; 5 | 6 | import com.opensource.netty.redis.proxy.commons.constants.RedisConstants; 7 | import com.opensource.netty.redis.proxy.commons.exception.LBRedisProxyFrameworkException; 8 | import com.opensource.netty.redis.proxy.commons.utils.StringUtils; 9 | import com.opensource.netty.redis.proxy.core.enums.ZkNodeType; 10 | import com.opensource.netty.redis.proxy.core.url.RedisProxyURL; 11 | 12 | 13 | /** 14 | * ZK 工具类 15 | * @author liubing 16 | * 17 | */ 18 | public class ZkUtils { 19 | 20 | public static String toServicePath(RedisProxyURL url) { 21 | return RedisConstants.ZOOKEEPER_REGISTRY_NAMESPACE ; 22 | } 23 | 24 | 25 | 26 | public static String toCommandPath(RedisProxyURL url) { 27 | return toServicePath(url) + RedisConstants.ZOOKEEPER_REGISTRY_COMMAND; 28 | } 29 | 30 | public static String toNodeTypePath(RedisProxyURL url, ZkNodeType nodeType) { 31 | String type; 32 | if (nodeType == ZkNodeType.AVAILABLE_SERVER) { 33 | type = "server"; 34 | } else if (nodeType == ZkNodeType.UNAVAILABLE_SERVER) { 35 | type = "unavailableServer"; 36 | } else if (nodeType == ZkNodeType.CLIENT) { 37 | type = "client"; 38 | } else { 39 | throw new LBRedisProxyFrameworkException(String.format("Failed to get nodeTypePath, url: %s type: %s", url, nodeType.toString())); 40 | } 41 | return toCommandPath(url) + RedisConstants.PATH_SEPARATOR + type; 42 | } 43 | 44 | public static String toNodePath(RedisProxyURL url,String parentPath, ZkNodeType nodeType) { 45 | if(StringUtils.isNotBlank(parentPath)){ 46 | return toNodeTypePath(url, nodeType)+ RedisConstants.PATH_SEPARATOR+parentPath+RedisConstants.PATH_SEPARATOR +url.getServerKey(); 47 | } 48 | return toNodeTypePath(url, nodeType)+ RedisConstants.PATH_SEPARATOR +url.getServerKey(); 49 | } 50 | 51 | } 52 | -------------------------------------------------------------------------------- /nredis-proxy-core/src/main/java/com/opensource/netty/redis/proxy/core/reply/IRedisReply.java: -------------------------------------------------------------------------------- 1 | package com.opensource.netty.redis.proxy.core.reply; 2 | 3 | import io.netty.buffer.ByteBuf; 4 | 5 | import com.opensource.netty.redis.proxy.core.enums.Type; 6 | 7 | /** 8 | * redis 回答 9 | * 10 | * @author liubing 11 | * 12 | */ 13 | public interface IRedisReply { 14 | 15 | /** 16 | * 获取类型 17 | * @return 18 | */ 19 | Type getType(); 20 | 21 | /** 22 | * 设置类型 23 | * @param type 24 | */ 25 | void setType(Type type); 26 | 27 | /** 28 | * 编码 29 | * @param out 30 | */ 31 | void encode(ByteBuf out); 32 | } 33 | -------------------------------------------------------------------------------- /nredis-proxy-core/src/main/java/com/opensource/netty/redis/proxy/core/reply/impl/AbstractRedisReply.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package com.opensource.netty.redis.proxy.core.reply.impl; 5 | 6 | import io.netty.buffer.ByteBuf; 7 | 8 | import com.opensource.netty.redis.proxy.commons.constants.RedisConstants; 9 | import com.opensource.netty.redis.proxy.core.enums.Type; 10 | import com.opensource.netty.redis.proxy.core.reply.IRedisReply; 11 | 12 | /** 13 | * @author liubing 14 | * 15 | */ 16 | public abstract class AbstractRedisReply implements IRedisReply { 17 | 18 | private Type type; 19 | 20 | /** 21 | * 22 | */ 23 | public AbstractRedisReply() { 24 | super(); 25 | } 26 | 27 | /** 28 | * @param type 29 | */ 30 | public AbstractRedisReply(Type type) { 31 | super(); 32 | this.type = type; 33 | } 34 | 35 | /* 36 | * (non-Javadoc) 37 | * 38 | * @see com.wanda.ffan.redis.proxy.core.reply.IRedisReply#getType() 39 | */ 40 | @Override 41 | public Type getType() { 42 | 43 | return type; 44 | } 45 | 46 | /* 47 | * (non-Javadoc) 48 | * 49 | * @see 50 | * com.wanda.ffan.redis.proxy.core.reply.IRedisReply#setType(com.wanda.ffan 51 | * .redis.proxy.core.enums.Type) 52 | */ 53 | @Override 54 | public void setType(Type type) { 55 | this.type = type; 56 | } 57 | 58 | public void writeCRLF(ByteBuf byteBuf) { 59 | byteBuf.writeByte(RedisConstants.CR_BYTE); 60 | byteBuf.writeByte(RedisConstants.LF_BYTE); 61 | } 62 | 63 | public void writeStart(ByteBuf byteBuf) { 64 | byteBuf.writeByte(type.getCode()); 65 | } 66 | 67 | 68 | /* 69 | * (non-Javadoc) 70 | * 71 | * @see 72 | * com.wanda.ffan.redis.proxy.core.reply.IRedisReply#encode(io.netty.buffer 73 | * .ByteBuf) 74 | */ 75 | @Override 76 | public void encode(ByteBuf out) { 77 | // TODO Auto-generated method stub 78 | writeStart(out); 79 | doEncode(out); 80 | } 81 | 82 | public abstract void doEncode(ByteBuf out); 83 | } 84 | -------------------------------------------------------------------------------- /nredis-proxy-core/src/main/java/com/opensource/netty/redis/proxy/core/reply/impl/BulkRedisReply.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package com.opensource.netty.redis.proxy.core.reply.impl; 5 | 6 | import com.opensource.netty.redis.proxy.commons.utils.ProtoUtils; 7 | import com.opensource.netty.redis.proxy.core.enums.Type; 8 | 9 | import io.netty.buffer.ByteBuf; 10 | 11 | /** 12 | * 13 | * @author liubing 14 | * 15 | */ 16 | public class BulkRedisReply extends CommonRedisReply { 17 | 18 | private int length; 19 | 20 | public BulkRedisReply(byte[] value) { 21 | this(); 22 | this.value = value; 23 | } 24 | 25 | public BulkRedisReply() { 26 | super(Type.BULK); 27 | } 28 | 29 | public void setLength(int length) { 30 | this.length = length; 31 | } 32 | 33 | /* 34 | * (non-Javadoc) 35 | * 36 | * @see 37 | * com.wanda.ffan.redis.proxy.core.reply.impl.AbstractRedisReply#doEncode 38 | * (io.netty.buffer.ByteBuf) 39 | */ 40 | @Override 41 | public void doEncode(ByteBuf out) { 42 | out.writeBytes(ProtoUtils.convertIntToByteArray(length)); 43 | writeCRLF(out); 44 | if (length > -1 && value != null) { 45 | out.writeBytes(value); 46 | writeCRLF(out); 47 | } 48 | } 49 | 50 | } 51 | -------------------------------------------------------------------------------- /nredis-proxy-core/src/main/java/com/opensource/netty/redis/proxy/core/reply/impl/CommonRedisReply.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package com.opensource.netty.redis.proxy.core.reply.impl; 5 | 6 | import com.opensource.netty.redis.proxy.core.enums.Type; 7 | 8 | /** 9 | * @author liubing 10 | * 11 | */ 12 | public abstract class CommonRedisReply extends AbstractRedisReply { 13 | 14 | protected byte[] value; 15 | 16 | public CommonRedisReply(Type type) { 17 | super(type); 18 | } 19 | 20 | public void setValue(byte[] value) { 21 | this.value = value; 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /nredis-proxy-core/src/main/java/com/opensource/netty/redis/proxy/core/reply/impl/ErrorRedisReply.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package com.opensource.netty.redis.proxy.core.reply.impl; 5 | 6 | import com.opensource.netty.redis.proxy.core.enums.Type; 7 | 8 | import io.netty.buffer.ByteBuf; 9 | 10 | /** 11 | * @author liubing 12 | * 13 | */ 14 | public class ErrorRedisReply extends CommonRedisReply { 15 | 16 | public ErrorRedisReply() { 17 | super(Type.ERROR); 18 | } 19 | 20 | public ErrorRedisReply(byte[] value) { 21 | this(); 22 | this.value = value; 23 | } 24 | 25 | /* 26 | * (non-Javadoc) 27 | * 28 | * @see 29 | * com.wanda.ffan.redis.proxy.core.reply.impl.AbstractRedisReply#doEncode 30 | * (io.netty.buffer.ByteBuf) 31 | */ 32 | @Override 33 | public void doEncode(ByteBuf out) { 34 | out.writeBytes(value); 35 | writeCRLF(out); 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /nredis-proxy-core/src/main/java/com/opensource/netty/redis/proxy/core/reply/impl/IntegerRedisReply.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package com.opensource.netty.redis.proxy.core.reply.impl; 5 | 6 | import com.opensource.netty.redis.proxy.core.enums.Type; 7 | 8 | import io.netty.buffer.ByteBuf; 9 | 10 | /** 11 | * @author liubing 12 | * 13 | */ 14 | public class IntegerRedisReply extends CommonRedisReply { 15 | 16 | public IntegerRedisReply() { 17 | super(Type.INTEGER); 18 | } 19 | 20 | public IntegerRedisReply(byte[] value) { 21 | this(); 22 | this.value = value; 23 | } 24 | 25 | /* 26 | * (non-Javadoc) 27 | * 28 | * @see 29 | * com.wanda.ffan.redis.proxy.core.reply.impl.AbstractRedisReply#doEncode 30 | * (io.netty.buffer.ByteBuf) 31 | */ 32 | @Override 33 | public void doEncode(ByteBuf out) { 34 | out.writeBytes(value); 35 | writeCRLF(out); 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /nredis-proxy-core/src/main/java/com/opensource/netty/redis/proxy/core/reply/impl/MultyBulkRedisReply.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package com.opensource.netty.redis.proxy.core.reply.impl; 5 | 6 | import java.util.ArrayList; 7 | import java.util.List; 8 | 9 | import com.opensource.netty.redis.proxy.commons.constants.RedisConstants; 10 | import com.opensource.netty.redis.proxy.commons.utils.ProtoUtils; 11 | import com.opensource.netty.redis.proxy.core.enums.Type; 12 | import com.opensource.netty.redis.proxy.core.reply.IRedisReply; 13 | 14 | import io.netty.buffer.ByteBuf; 15 | 16 | /** 17 | * @author liubing 18 | * 19 | */ 20 | public class MultyBulkRedisReply extends CommonRedisReply { 21 | 22 | protected List list = new ArrayList(); 23 | 24 | private int count; 25 | 26 | public void setCount(int count) { 27 | this.count = count; 28 | } 29 | 30 | public MultyBulkRedisReply() { 31 | super(Type.MULTYBULK); 32 | } 33 | 34 | /* 35 | * (non-Javadoc) 36 | * 37 | * @see 38 | * com.wanda.ffan.redis.proxy.core.reply.impl.AbstractRedisReply#doEncode 39 | * (io.netty.buffer.ByteBuf) 40 | */ 41 | @Override 42 | public void doEncode(ByteBuf out) { 43 | out.writeBytes(ProtoUtils.convertIntToByteArray(count)); 44 | writeCRLF(out); 45 | for (IRedisReply reply : list) { 46 | if (reply instanceof IntegerRedisReply) { 47 | if (value == null&&count==0) { 48 | out.writeByte(RedisConstants.COLON_BYTE); 49 | out.writeBytes(ProtoUtils.convertIntToByteArray(-1)); 50 | writeCRLF(out); 51 | } else { 52 | out.writeByte(RedisConstants.COLON_BYTE); 53 | out.writeBytes(ProtoUtils 54 | .convertIntToByteArray(((IntegerRedisReply) reply).value.length)); 55 | writeCRLF(out); 56 | out.writeBytes(((IntegerRedisReply) reply).value); 57 | writeCRLF(out); 58 | } 59 | 60 | } else if (reply instanceof BulkRedisReply) { 61 | if (value == null&&count==0) { 62 | out.writeByte(RedisConstants.DOLLAR_BYTE); 63 | out.writeBytes(ProtoUtils.convertIntToByteArray(-1)); 64 | writeCRLF(out); 65 | } else { 66 | out.writeByte(RedisConstants.DOLLAR_BYTE); 67 | out.writeBytes(ProtoUtils 68 | .convertIntToByteArray(((BulkRedisReply) reply).value.length)); 69 | writeCRLF(out); 70 | out.writeBytes(((BulkRedisReply) reply).value); 71 | writeCRLF(out); 72 | } 73 | 74 | } 75 | } 76 | } 77 | 78 | public void addReply(IRedisReply reply) { 79 | list.add(reply); 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /nredis-proxy-core/src/main/java/com/opensource/netty/redis/proxy/core/reply/impl/StatusRedisReply.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package com.opensource.netty.redis.proxy.core.reply.impl; 5 | 6 | import com.opensource.netty.redis.proxy.core.enums.Type; 7 | 8 | import io.netty.buffer.ByteBuf; 9 | 10 | /** 11 | * redis server 状态回答 12 | * @author liubing 13 | * 14 | */ 15 | public class StatusRedisReply extends CommonRedisReply { 16 | 17 | public StatusRedisReply() { 18 | super(Type.STATUS); 19 | } 20 | 21 | public StatusRedisReply(byte[] value) { 22 | this(); 23 | this.value = value; 24 | } 25 | 26 | /* 27 | * (non-Javadoc) 28 | * 29 | * @see 30 | * com.wanda.ffan.redis.proxy.core.reply.impl.AbstractRedisReply#doEncode 31 | * (io.netty.buffer.ByteBuf) 32 | */ 33 | @Override 34 | public void doEncode(ByteBuf out) { 35 | // TODO Auto-generated method stub 36 | out.writeBytes(value); 37 | writeCRLF(out); 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /nredis-proxy-failover/.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /nredis-proxy-failover/.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | -------------------------------------------------------------------------------- /nredis-proxy-failover/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | nredis-proxy-fallover 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.wst.jsdt.core.javascriptValidator 10 | 11 | 12 | 13 | 14 | org.eclipse.jdt.core.javabuilder 15 | 16 | 17 | 18 | 19 | org.eclipse.wst.common.project.facet.core.builder 20 | 21 | 22 | 23 | 24 | org.eclipse.wst.validation.validationbuilder 25 | 26 | 27 | 28 | 29 | org.eclipse.m2e.core.maven2Builder 30 | 31 | 32 | 33 | 34 | 35 | org.eclipse.jem.workbench.JavaEMFNature 36 | org.eclipse.wst.common.modulecore.ModuleCoreNature 37 | org.eclipse.jdt.core.javanature 38 | org.eclipse.m2e.core.maven2Nature 39 | org.eclipse.wst.common.project.facet.core.nature 40 | org.eclipse.wst.jsdt.core.jsNature 41 | 42 | 43 | -------------------------------------------------------------------------------- /nredis-proxy-failover/.settings/.jsdtscope: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /nredis-proxy-failover/.settings/org.eclipse.core.resources.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | encoding//src/main/java=UTF-8 3 | encoding//src/main/resources=UTF-8 4 | encoding/=UTF-8 5 | -------------------------------------------------------------------------------- /nredis-proxy-failover/.settings/org.eclipse.jdt.core.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled 3 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.7 4 | org.eclipse.jdt.core.compiler.compliance=1.7 5 | org.eclipse.jdt.core.compiler.problem.assertIdentifier=error 6 | org.eclipse.jdt.core.compiler.problem.enumIdentifier=error 7 | org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning 8 | org.eclipse.jdt.core.compiler.source=1.7 9 | -------------------------------------------------------------------------------- /nredis-proxy-failover/.settings/org.eclipse.m2e.core.prefs: -------------------------------------------------------------------------------- 1 | activeProfiles= 2 | eclipse.preferences.version=1 3 | resolveWorkspaceProjects=true 4 | version=1 5 | -------------------------------------------------------------------------------- /nredis-proxy-failover/.settings/org.eclipse.wst.common.component: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | uses 9 | 10 | 11 | uses 12 | 13 | 14 | uses 15 | 16 | 17 | uses 18 | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /nredis-proxy-failover/.settings/org.eclipse.wst.common.project.facet.core.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /nredis-proxy-failover/.settings/org.eclipse.wst.jsdt.ui.superType.container: -------------------------------------------------------------------------------- 1 | org.eclipse.wst.jsdt.launching.baseBrowserLibrary -------------------------------------------------------------------------------- /nredis-proxy-failover/.settings/org.eclipse.wst.jsdt.ui.superType.name: -------------------------------------------------------------------------------- 1 | Window -------------------------------------------------------------------------------- /nredis-proxy-failover/.settings/org.eclipse.wst.validation.prefs: -------------------------------------------------------------------------------- 1 | disabled=06target 2 | eclipse.preferences.version=1 3 | -------------------------------------------------------------------------------- /nredis-proxy-failover/src/main/java/com/opensource/netty/redis/proxy/monitor/spring/helper/RedisMonitorConfigurationHelper.java: -------------------------------------------------------------------------------- 1 | package com.opensource.netty.redis.proxy.monitor.spring.helper; 2 | 3 | import com.opensource.netty.redis.proxy.monitor.spring.bean.RedisMonitorConfiguration; 4 | 5 | /** 6 | * RedisMonitorConfigurationHelper获取RedisMonitorConfiguration实例 7 | * 8 | * @author wangyang 9 | */ 10 | public class RedisMonitorConfigurationHelper { 11 | private static class InstanceHolder { 12 | private static final RedisMonitorConfigurationHelper instance = new RedisMonitorConfigurationHelper(); 13 | } 14 | 15 | public static RedisMonitorConfigurationHelper getInstance() { 16 | return InstanceHolder.instance; 17 | } 18 | 19 | 20 | private static final RedisMonitorConfiguration redisMonitorConfiguration = SpringFactory.getBean("redisMonitorConfiguration"); 21 | 22 | 23 | public RedisMonitorConfiguration getRedisMonitorConfigurationInstance() { 24 | return redisMonitorConfiguration; 25 | } 26 | 27 | 28 | } 29 | -------------------------------------------------------------------------------- /nredis-proxy-failover/src/main/java/com/opensource/netty/redis/proxy/monitor/spring/helper/SpringFactory.java: -------------------------------------------------------------------------------- 1 | package com.opensource.netty.redis.proxy.monitor.spring.helper; 2 | 3 | import org.apache.log4j.LogManager; 4 | import org.apache.log4j.Logger; 5 | import org.springframework.beans.BeansException; 6 | import org.springframework.beans.factory.BeanFactory; 7 | import org.springframework.beans.factory.BeanFactoryAware; 8 | /** 9 | * SpringFactory 10 | * 11 | * @author wangyang 12 | */ 13 | public class SpringFactory implements BeanFactoryAware { 14 | 15 | private static Logger logger = LogManager.getLogger(SpringFactory.class); 16 | private static BeanFactory beanFactory; 17 | 18 | public SpringFactory() { 19 | } 20 | 21 | @Override 22 | public void setBeanFactory(BeanFactory factory) throws BeansException { 23 | logger.info("初始化beanFactory=============="); 24 | beanFactory = factory; 25 | } 26 | 27 | @SuppressWarnings("unchecked") 28 | public static T getBean(String beanName) { 29 | if (null == beanFactory) { 30 | logger.error("beanFactory 为空============"); 31 | } 32 | if (null != beanFactory) { 33 | return (T) beanFactory.getBean(beanName); 34 | } 35 | return null; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /nredis-proxy-failover/src/main/resources/applicationContext.xml: -------------------------------------------------------------------------------- 1 | 2 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /nredis-proxy-failover/src/main/resources/log4j.properties: -------------------------------------------------------------------------------- 1 | log4j.rootCategory=INFO, stdout 2 | 3 | log4j.appender.stdout=org.apache.log4j.ConsoleAppender 4 | log4j.appender.stdout.layout=org.apache.log4j.PatternLayout 5 | log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - <%m>%n 6 | 7 | log4j.category.org.springframework.data.redis.listener=TRACE 8 | 9 | # for debugging datasource initialization 10 | # log4j.category.test.jdbc=DEBUG 11 | -------------------------------------------------------------------------------- /nredis-proxy-failover/src/main/resources/timer.xml: -------------------------------------------------------------------------------- 1 | 2 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | monitorMasterSlaves 25 | 26 | 27 | false 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 0 0/3 * * * ? 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /nredis-proxy-failover/src/main/webapp/WEB-INF/web.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | nredis-proxy-fallover 6 | 7 | 8 | contextConfigLocation 9 | classpath:applicationContext.xml 10 | 11 | 12 | 13 | 14 | 15 | 16 | org.springframework.web.context.ContextLoaderListener 17 | 18 | 19 | org.springframework.web.context.request.RequestContextListener 20 | 21 | 22 | 23 | spring-web 24 | org.springframework.web.servlet.DispatcherServlet 25 | 26 | transformWsdlLocations 27 | true 28 | 29 | 30 | contextConfigLocation 31 | 32 | 33 | 34 | debug 35 | false 36 | 37 | 0 38 | 39 | 40 | spring-web 41 | /* 42 | 43 | 44 | 45 | 46 | 47 | 48 | encodingFilter 49 | org.springframework.web.filter.CharacterEncodingFilter 50 | 51 | encoding 52 | UTF-8 53 | 54 | 55 | 56 | encodingFilter 57 | /* 58 | 59 | 60 | 61 | index.html 62 | 63 | -------------------------------------------------------------------------------- /nredis-proxy-failover/src/main/webapp/index.jsp: -------------------------------------------------------------------------------- 1 | 2 | 3 |

Hello World!

4 | 5 | 6 | -------------------------------------------------------------------------------- /nredis-proxy-net/.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /nredis-proxy-net/.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | -------------------------------------------------------------------------------- /nredis-proxy-net/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | nredis-proxy-net 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.jdt.core.javabuilder 10 | 11 | 12 | 13 | 14 | org.eclipse.m2e.core.maven2Builder 15 | 16 | 17 | 18 | 19 | 20 | org.eclipse.jdt.core.javanature 21 | org.eclipse.m2e.core.maven2Nature 22 | 23 | 24 | -------------------------------------------------------------------------------- /nredis-proxy-net/.settings/org.eclipse.core.resources.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | encoding//src/main/java=UTF-8 3 | encoding/=UTF-8 4 | -------------------------------------------------------------------------------- /nredis-proxy-net/.settings/org.eclipse.jdt.core.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.7 3 | org.eclipse.jdt.core.compiler.compliance=1.7 4 | org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning 5 | org.eclipse.jdt.core.compiler.source=1.7 6 | -------------------------------------------------------------------------------- /nredis-proxy-net/.settings/org.eclipse.m2e.core.prefs: -------------------------------------------------------------------------------- 1 | activeProfiles= 2 | eclipse.preferences.version=1 3 | resolveWorkspaceProjects=true 4 | version=1 5 | -------------------------------------------------------------------------------- /nredis-proxy-net/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.opensource 7 | nredis-proxy 8 | 1.0 9 | 10 | com.opensource 11 | nredis-proxy-net 12 | 1.0 13 | nredis-proxy-net 14 | http://maven.apache.org 15 | 16 | UTF-8 17 | 18 | 19 | 20 | junit 21 | junit 22 | 23 | 24 | 25 | com.opensource 26 | nredis-proxy-core 27 | 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /nredis-proxy-net/src/main/java/com/opensource/netty/redis/proxy/net/client/LBRedisConnectionFactory.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package com.opensource.netty.redis.proxy.net.client; 5 | 6 | import com.opensource.netty.redis.proxy.core.connection.IConnection; 7 | import com.opensource.netty.redis.proxy.pool.LBRedisProxyPooledObjectFactory; 8 | import com.opensource.netty.redis.proxy.pool.exception.LBRedisProxyPoolException; 9 | 10 | 11 | /** 12 | * @author liubing 13 | * 14 | */ 15 | public class LBRedisConnectionFactory implements LBRedisProxyPooledObjectFactory{ 16 | 17 | private LBRedisClient ffanRedisClient; 18 | 19 | 20 | /** 21 | * @param ffanRedisClient 22 | */ 23 | public LBRedisConnectionFactory(LBRedisClient ffanRedisClient) { 24 | super(); 25 | this.ffanRedisClient = ffanRedisClient; 26 | } 27 | 28 | 29 | 30 | @Override 31 | public IConnection createInstance() throws LBRedisProxyPoolException { 32 | LBRedisConnection ffanRedisConnection=new LBRedisConnection(ffanRedisClient); 33 | ffanRedisConnection.open(); 34 | return ffanRedisConnection; 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /nredis-proxy-net/src/main/java/com/opensource/netty/redis/proxy/net/client/support/LBRedisClientInHandler.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package com.opensource.netty.redis.proxy.net.client.support; 5 | 6 | import com.opensource.netty.redis.proxy.core.connection.IConnectionCallBack; 7 | import com.opensource.netty.redis.proxy.core.log.impl.LoggerUtils; 8 | import com.opensource.netty.redis.proxy.core.reply.IRedisReply; 9 | 10 | import io.netty.channel.ChannelHandlerContext; 11 | import io.netty.channel.SimpleChannelInboundHandler; 12 | 13 | /** 14 | * 目标服务器与客户端通道写入 15 | * @author liubing 16 | * 17 | */ 18 | public class LBRedisClientInHandler extends SimpleChannelInboundHandler { 19 | 20 | @Override 21 | protected void channelRead0(ChannelHandlerContext ctx, IRedisReply msg) 22 | throws Exception { 23 | IConnectionCallBack callBack = ctx.channel().attr(LBRedisClientOutHandler.CALLBACK_KEY).get(); 24 | if(callBack!=null){ 25 | callBack.handleReply(msg); 26 | }else{ 27 | LoggerUtils.error(ctx.channel().remoteAddress().toString()+" has no callBack"); 28 | } 29 | 30 | } 31 | 32 | @Override 33 | public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) 34 | throws Exception { 35 | 36 | super.exceptionCaught(ctx, cause); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /nredis-proxy-net/src/main/java/com/opensource/netty/redis/proxy/net/client/support/LBRedisClientOutHandler.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package com.opensource.netty.redis.proxy.net.client.support; 5 | 6 | import com.opensource.netty.redis.proxy.core.command.impl.RedisCommand; 7 | import com.opensource.netty.redis.proxy.core.connection.IConnectionCallBack; 8 | import com.opensource.netty.redis.proxy.core.log.impl.LoggerUtils; 9 | 10 | import io.netty.channel.ChannelHandlerContext; 11 | import io.netty.channel.ChannelOutboundHandlerAdapter; 12 | import io.netty.channel.ChannelPromise; 13 | import io.netty.util.AttributeKey; 14 | 15 | /** 16 | * 解码处理 17 | * 18 | * @author liubing 19 | * 20 | */ 21 | public class LBRedisClientOutHandler extends ChannelOutboundHandlerAdapter { 22 | 23 | public static final AttributeKey CALLBACK_KEY = AttributeKey.valueOf("CALLBACK_KEY"); 24 | @Override 25 | public void write(ChannelHandlerContext ctx, Object msg, 26 | ChannelPromise promise) throws Exception { 27 | if(msg instanceof RedisCommand){ 28 | ctx.write(msg, promise); 29 | }else{ 30 | LoggerUtils.error("write redis server msg not instanceof RedisCommand"); 31 | } 32 | 33 | 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /nredis-proxy-pool/.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /nredis-proxy-pool/.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | -------------------------------------------------------------------------------- /nredis-proxy-pool/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | nredis-proxy-pool 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.wst.common.project.facet.core.builder 10 | 11 | 12 | 13 | 14 | org.eclipse.jdt.core.javabuilder 15 | 16 | 17 | 18 | 19 | org.eclipse.wst.validation.validationbuilder 20 | 21 | 22 | 23 | 24 | org.eclipse.m2e.core.maven2Builder 25 | 26 | 27 | 28 | 29 | 30 | org.eclipse.jem.workbench.JavaEMFNature 31 | org.eclipse.wst.common.modulecore.ModuleCoreNature 32 | org.eclipse.jdt.core.javanature 33 | org.eclipse.m2e.core.maven2Nature 34 | org.eclipse.wst.common.project.facet.core.nature 35 | 36 | 37 | -------------------------------------------------------------------------------- /nredis-proxy-pool/.settings/org.eclipse.core.resources.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | encoding//src/main/java=UTF-8 3 | encoding/=UTF-8 4 | -------------------------------------------------------------------------------- /nredis-proxy-pool/.settings/org.eclipse.jdt.core.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled 3 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.7 4 | org.eclipse.jdt.core.compiler.compliance=1.7 5 | org.eclipse.jdt.core.compiler.problem.assertIdentifier=error 6 | org.eclipse.jdt.core.compiler.problem.enumIdentifier=error 7 | org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning 8 | org.eclipse.jdt.core.compiler.source=1.7 9 | -------------------------------------------------------------------------------- /nredis-proxy-pool/.settings/org.eclipse.m2e.core.prefs: -------------------------------------------------------------------------------- 1 | activeProfiles= 2 | eclipse.preferences.version=1 3 | resolveWorkspaceProjects=true 4 | version=1 5 | -------------------------------------------------------------------------------- /nredis-proxy-pool/.settings/org.eclipse.wst.common.component: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /nredis-proxy-pool/.settings/org.eclipse.wst.common.project.facet.core.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /nredis-proxy-pool/.settings/org.eclipse.wst.validation.prefs: -------------------------------------------------------------------------------- 1 | disabled=06target 2 | eclipse.preferences.version=1 3 | -------------------------------------------------------------------------------- /nredis-proxy-pool/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.opensource 7 | nredis-proxy 8 | 1.0 9 | 10 | com.opensource 11 | nredis-proxy-pool 12 | 1.0 13 | nredis-proxy-pool 14 | http://maven.apache.org 15 | 16 | UTF-8 17 | 18 | 19 | 20 | junit 21 | junit 22 | test 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /nredis-proxy-pool/src/main/java/com/opensource/netty/redis/proxy/pool/LBRedisProxyIdleEntriesQueue.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package com.opensource.netty.redis.proxy.pool; 5 | 6 | import com.opensource.netty.redis.proxy.pool.commons.Pool; 7 | 8 | 9 | /** 10 | * 空闲队列接口 11 | * @author liubing 12 | * 13 | */ 14 | public interface LBRedisProxyIdleEntriesQueue { 15 | 16 | /** 17 | * 18 | * @return 19 | */ 20 | LBRedisProxyPoolEntry poll(); 21 | 22 | /** 23 | * 24 | * @param entry 25 | * @return 26 | * @throws NullPointerException 27 | */ 28 | boolean offer(LBRedisProxyPoolEntry entry) throws NullPointerException; 29 | 30 | 31 | public int getIdleEntriesCount(); 32 | 33 | 34 | public void clear(); 35 | } 36 | -------------------------------------------------------------------------------- /nredis-proxy-pool/src/main/java/com/opensource/netty/redis/proxy/pool/LBRedisProxyPool.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package com.opensource.netty.redis.proxy.pool; 5 | 6 | import java.util.concurrent.TimeUnit; 7 | import java.util.concurrent.TimeoutException; 8 | 9 | import com.opensource.netty.redis.proxy.pool.commons.LBRedisProxyPoolConfig; 10 | import com.opensource.netty.redis.proxy.pool.commons.Pool; 11 | import com.opensource.netty.redis.proxy.pool.exception.LBRedisProxyPoolException; 12 | 13 | 14 | /** 15 | * @author liubing 16 | * 17 | */ 18 | public interface LBRedisProxyPool { 19 | 20 | LBRedisProxyPoolConfig getPoolConfig(); 21 | 22 | LBRedisProxyPoolEntry borrowEntry() throws InterruptedException, TimeoutException,LBRedisProxyPoolException; 23 | 24 | LBRedisProxyPoolEntry borrowEntry(boolean createNew) throws InterruptedException, 25 | TimeoutException, LBRedisProxyPoolException; 26 | 27 | LBRedisProxyPoolEntry borrowEntry(long timeout, TimeUnit unit) 28 | throws InterruptedException, TimeoutException, LBRedisProxyPoolException; 29 | 30 | LBRedisProxyPoolEntry borrowEntry(boolean createNew, long timeout, TimeUnit unit) 31 | throws InterruptedException, TimeoutException, LBRedisProxyPoolException; 32 | 33 | LBRedisProxyPoolEntry tryBorrowEntry() throws LBRedisProxyPoolException; 34 | 35 | LBRedisProxyPoolEntry tryBorrowEntry(boolean createNew) throws LBRedisProxyPoolException; 36 | 37 | void returnEntry(LBRedisProxyPoolEntry entry) throws NullPointerException; 38 | 39 | void clear(); 40 | } 41 | -------------------------------------------------------------------------------- /nredis-proxy-pool/src/main/java/com/opensource/netty/redis/proxy/pool/LBRedisProxyPoolEntry.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package com.opensource.netty.redis.proxy.pool; 5 | 6 | import com.opensource.netty.redis.proxy.pool.commons.LBRedisProxyPoolEntryState; 7 | import com.opensource.netty.redis.proxy.pool.commons.Pool; 8 | /** 9 | * @author liubing 10 | * 11 | */ 12 | public interface LBRedisProxyPoolEntry { 13 | 14 | T getObject(); 15 | 16 | 17 | LBRedisProxyPoolEntryState getState(); 18 | } 19 | -------------------------------------------------------------------------------- /nredis-proxy-pool/src/main/java/com/opensource/netty/redis/proxy/pool/LBRedisProxyPoolEntryFactory.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package com.opensource.netty.redis.proxy.pool; 5 | 6 | import com.opensource.netty.redis.proxy.pool.commons.Pool; 7 | import com.opensource.netty.redis.proxy.pool.exception.LBRedisProxyPoolException; 8 | 9 | 10 | /** 11 | * @author liubing 12 | * 13 | */ 14 | public interface LBRedisProxyPoolEntryFactory { 15 | 16 | LBRedisProxyPoolEntry createPoolEntry() throws LBRedisProxyPoolException; 17 | } 18 | -------------------------------------------------------------------------------- /nredis-proxy-pool/src/main/java/com/opensource/netty/redis/proxy/pool/LBRedisProxyPooledObjectFactory.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package com.opensource.netty.redis.proxy.pool; 5 | 6 | import com.opensource.netty.redis.proxy.pool.commons.Pool; 7 | import com.opensource.netty.redis.proxy.pool.exception.LBRedisProxyPoolException; 8 | 9 | 10 | /** 11 | * @author liubing 12 | * 13 | */ 14 | public interface LBRedisProxyPooledObjectFactory { 15 | 16 | T createInstance() throws LBRedisProxyPoolException; 17 | 18 | } 19 | -------------------------------------------------------------------------------- /nredis-proxy-pool/src/main/java/com/opensource/netty/redis/proxy/pool/commons/LBRedisProxyPoolEntryState.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package com.opensource.netty.redis.proxy.pool.commons; 5 | 6 | import java.util.concurrent.atomic.AtomicBoolean; 7 | import java.util.concurrent.atomic.AtomicLong; 8 | /** 9 | * @author liubing 10 | * 11 | */ 12 | public class LBRedisProxyPoolEntryState { 13 | 14 | private final long startAt = System.currentTimeMillis(); 15 | 16 | private AtomicLong lastValidatedAt = new AtomicLong( 17 | System.currentTimeMillis()); 18 | 19 | private AtomicBoolean valid = new AtomicBoolean(true); 20 | 21 | public long getStartAt() { 22 | return startAt; 23 | } 24 | 25 | /** 26 | * Get the last time the validity {@link JdPoolEntry} has been confirmed. 27 | * 28 | * @return lastValidatedAt 29 | * */ 30 | public long getLastValidatedAt() { 31 | return lastValidatedAt.longValue(); 32 | } 33 | 34 | /** 35 | * Set lastValidatedAt. 36 | * 37 | * @param lastValidatedAt 38 | * */ 39 | public void setLastValidatedAt(long lastValidatedAt) { 40 | this.lastValidatedAt.set(lastValidatedAt); 41 | } 42 | 43 | /** 44 | * Get validity of {@link JdPoolEntry}. 45 | * */ 46 | public boolean isValid() { 47 | return valid.get(); 48 | } 49 | 50 | /** 51 | * Compare and set valid 52 | * 53 | * @param expect 54 | * @param update 55 | * @return true, if succeeded 56 | * @see AtomicBoolean#compareAndSet(boolean, boolean) 57 | * */ 58 | public boolean compareAndSetValid(boolean expect, boolean update) { 59 | return valid.compareAndSet(expect, update); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /nredis-proxy-pool/src/main/java/com/opensource/netty/redis/proxy/pool/commons/Pool.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package com.opensource.netty.redis.proxy.pool.commons; 5 | 6 | /** 7 | * 连接池接口 8 | * @author liubing 9 | * 10 | */ 11 | public interface Pool { 12 | 13 | } 14 | -------------------------------------------------------------------------------- /nredis-proxy-pool/src/main/java/com/opensource/netty/redis/proxy/pool/exception/LBRedisProxyPoolException.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package com.opensource.netty.redis.proxy.pool.exception; 5 | 6 | /** 7 | * @author liubing 8 | * 自定义连接池exception 9 | */ 10 | public class LBRedisProxyPoolException extends Exception { 11 | 12 | /** 13 | * 14 | */ 15 | private static final long serialVersionUID = 1172816022950399557L; 16 | 17 | public LBRedisProxyPoolException() { 18 | super(); 19 | } 20 | 21 | public LBRedisProxyPoolException(String arg0, Throwable arg1) { 22 | super(arg0, arg1); 23 | } 24 | 25 | public LBRedisProxyPoolException(String arg0) { 26 | super(arg0); 27 | } 28 | 29 | public LBRedisProxyPoolException(Throwable arg0) { 30 | super(arg0); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /nredis-proxy-pool/src/main/java/com/opensource/netty/redis/proxy/pool/exception/LBRedisProxyPoolPropertyValidationException.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package com.opensource.netty.redis.proxy.pool.exception; 5 | 6 | /** 7 | * @author liubing 8 | * 9 | */ 10 | public class LBRedisProxyPoolPropertyValidationException extends Exception { 11 | 12 | /** 13 | * 14 | */ 15 | private static final long serialVersionUID = 1420614214978891385L; 16 | 17 | public LBRedisProxyPoolPropertyValidationException(String message) { 18 | super(message); 19 | } 20 | 21 | public LBRedisProxyPoolPropertyValidationException(String message, Throwable cause) { 22 | super(message, cause); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /nredis-proxy-pool/src/main/java/com/opensource/netty/redis/proxy/pool/impl/LBRedisProxyBasicPoolEntry.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package com.opensource.netty.redis.proxy.pool.impl; 5 | 6 | import com.opensource.netty.redis.proxy.pool.LBRedisProxyPoolEntry; 7 | import com.opensource.netty.redis.proxy.pool.commons.LBRedisProxyPoolEntryState; 8 | import com.opensource.netty.redis.proxy.pool.commons.Pool; 9 | 10 | 11 | /** 12 | * @author liubing 13 | * 14 | */ 15 | public class LBRedisProxyBasicPoolEntry implements LBRedisProxyPoolEntry { 16 | 17 | private final T object; 18 | 19 | private final LBRedisProxyPoolEntryState state; 20 | 21 | public LBRedisProxyBasicPoolEntry(T object) { 22 | super(); 23 | this.object = object; 24 | this.state = new LBRedisProxyPoolEntryState(); 25 | } 26 | 27 | /* (non-Javadoc) 28 | * @see com.wanda.ffan.rpc.pool.FfanRpcPoolEntry#getObject() 29 | */ 30 | @Override 31 | public T getObject() { 32 | // TODO Auto-generated method stub 33 | return object; 34 | } 35 | 36 | /* (non-Javadoc) 37 | * @see com.wanda.ffan.rpc.pool.FfanRpcPoolEntry#getState() 38 | */ 39 | @Override 40 | public LBRedisProxyPoolEntryState getState() { 41 | // TODO Auto-generated method stub 42 | return state; 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /nredis-proxy-pool/src/main/java/com/opensource/netty/redis/proxy/pool/impl/LBRedisProxyPoolBasicEntryFactory.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package com.opensource.netty.redis.proxy.pool.impl; 5 | 6 | import com.opensource.netty.redis.proxy.pool.LBRedisProxyPoolEntry; 7 | import com.opensource.netty.redis.proxy.pool.LBRedisProxyPoolEntryFactory; 8 | import com.opensource.netty.redis.proxy.pool.LBRedisProxyPooledObjectFactory; 9 | import com.opensource.netty.redis.proxy.pool.commons.Pool; 10 | import com.opensource.netty.redis.proxy.pool.exception.LBRedisProxyPoolException; 11 | 12 | 13 | 14 | /** 15 | * @author liubing 16 | * 17 | */ 18 | public class LBRedisProxyPoolBasicEntryFactory implements LBRedisProxyPoolEntryFactory { 19 | 20 | private final LBRedisProxyPooledObjectFactory ffanRpcPooledObjectFactory; 21 | 22 | 23 | public LBRedisProxyPoolBasicEntryFactory( 24 | LBRedisProxyPooledObjectFactory ffanRpcPoolBasicEntryFactory) { 25 | super(); 26 | this.ffanRpcPooledObjectFactory = ffanRpcPoolBasicEntryFactory; 27 | } 28 | 29 | 30 | /* (non-Javadoc) 31 | * @see com.wanda.ffan.rpc.pool.FfanRpcPoolEntryFactory#createPoolEntry() 32 | */ 33 | @Override 34 | public LBRedisProxyPoolEntry createPoolEntry() throws LBRedisProxyPoolException { 35 | // TODO Auto-generated method stub 36 | T object = null; 37 | try { 38 | object = ffanRpcPooledObjectFactory.createInstance(); 39 | return new LBRedisProxyBasicPoolEntry(object); 40 | } catch (LBRedisProxyPoolException e) { 41 | throw e; 42 | } 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /nredis-proxy-pool/src/main/java/com/opensource/netty/redis/proxy/pool/impl/LBRedisProxyPoolBasicIdleEntriesQueue.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package com.opensource.netty.redis.proxy.pool.impl; 5 | 6 | import java.util.concurrent.ArrayBlockingQueue; 7 | 8 | import com.opensource.netty.redis.proxy.pool.LBRedisProxyIdleEntriesQueue; 9 | import com.opensource.netty.redis.proxy.pool.LBRedisProxyPoolEntry; 10 | import com.opensource.netty.redis.proxy.pool.commons.LBRedisProxyPoolConfig; 11 | import com.opensource.netty.redis.proxy.pool.commons.Pool; 12 | 13 | 14 | 15 | /** 16 | * 队列实现类 17 | * @author liubing 18 | * 19 | */ 20 | public class LBRedisProxyPoolBasicIdleEntriesQueue implements LBRedisProxyIdleEntriesQueue { 21 | 22 | private final ArrayBlockingQueue> idleEntries; 23 | 24 | public LBRedisProxyPoolBasicIdleEntriesQueue(LBRedisProxyPoolConfig config) { 25 | idleEntries = new ArrayBlockingQueue>( 26 | config.getMaxIdleEntries()); 27 | } 28 | 29 | @Override 30 | public LBRedisProxyPoolEntry poll() { 31 | 32 | // TODO Auto-generated method stub 33 | LBRedisProxyPoolEntry idle = idleEntries.poll(); 34 | return idle; 35 | } 36 | 37 | @Override 38 | public boolean offer(LBRedisProxyPoolEntry entry) throws NullPointerException { 39 | // TODO Auto-generated method stub 40 | if (entry == null) 41 | throw new NullPointerException("entry is null."); 42 | if (!entry.getState().isValid()) 43 | return false; 44 | 45 | boolean offerSuccessful = idleEntries.offer(entry); 46 | return offerSuccessful; 47 | } 48 | 49 | public ArrayBlockingQueue> getIdleEntries() { 50 | return idleEntries; 51 | } 52 | 53 | @Override 54 | public int getIdleEntriesCount() { 55 | // TODO Auto-generated method stub 56 | return idleEntries.size(); 57 | } 58 | 59 | @Override 60 | public void clear() { 61 | // TODO Auto-generated method stub 62 | 63 | idleEntries.clear(); 64 | } 65 | 66 | 67 | } 68 | -------------------------------------------------------------------------------- /nredis-proxy-register/.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /nredis-proxy-register/.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | -------------------------------------------------------------------------------- /nredis-proxy-register/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | nredis-proxy-register 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.wst.common.project.facet.core.builder 10 | 11 | 12 | 13 | 14 | org.eclipse.jdt.core.javabuilder 15 | 16 | 17 | 18 | 19 | org.eclipse.wst.validation.validationbuilder 20 | 21 | 22 | 23 | 24 | org.eclipse.m2e.core.maven2Builder 25 | 26 | 27 | 28 | 29 | 30 | org.eclipse.jem.workbench.JavaEMFNature 31 | org.eclipse.wst.common.modulecore.ModuleCoreNature 32 | org.eclipse.jdt.core.javanature 33 | org.eclipse.m2e.core.maven2Nature 34 | org.eclipse.wst.common.project.facet.core.nature 35 | 36 | 37 | -------------------------------------------------------------------------------- /nredis-proxy-register/.settings/org.eclipse.core.resources.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | encoding//src/main/java=UTF-8 3 | encoding/=UTF-8 4 | -------------------------------------------------------------------------------- /nredis-proxy-register/.settings/org.eclipse.jdt.core.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled 3 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.7 4 | org.eclipse.jdt.core.compiler.compliance=1.7 5 | org.eclipse.jdt.core.compiler.problem.assertIdentifier=error 6 | org.eclipse.jdt.core.compiler.problem.enumIdentifier=error 7 | org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning 8 | org.eclipse.jdt.core.compiler.source=1.7 9 | -------------------------------------------------------------------------------- /nredis-proxy-register/.settings/org.eclipse.m2e.core.prefs: -------------------------------------------------------------------------------- 1 | activeProfiles= 2 | eclipse.preferences.version=1 3 | resolveWorkspaceProjects=true 4 | version=1 5 | -------------------------------------------------------------------------------- /nredis-proxy-register/.settings/org.eclipse.wst.common.component: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /nredis-proxy-register/.settings/org.eclipse.wst.common.project.facet.core.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /nredis-proxy-register/.settings/org.eclipse.wst.validation.prefs: -------------------------------------------------------------------------------- 1 | disabled=06target 2 | eclipse.preferences.version=1 3 | -------------------------------------------------------------------------------- /nredis-proxy-register/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.opensource 7 | nredis-proxy 8 | 1.0 9 | 10 | com.opensource 11 | nredis-proxy-register 12 | 1.0 13 | nredis-proxy-register 14 | http://maven.apache.org 15 | 16 | UTF-8 17 | 18 | 19 | 20 | junit 21 | junit 22 | test 23 | 24 | 25 | org.apache.zookeeper 26 | zookeeper 27 | 28 | 29 | com.opensource 30 | nredis-proxy-core 31 | 32 | 33 | com.alibaba 34 | fastjson 35 | 36 | 37 | 38 | -------------------------------------------------------------------------------- /nredis-proxy-register/src/main/java/com/opensource/netty/redis/proxy/zk/registry/ZookeeperRegistryFactory.java: -------------------------------------------------------------------------------- 1 | 2 | package com.opensource.netty.redis.proxy.zk.registry; 3 | 4 | 5 | import org.I0Itec.zkclient.ZkClient; 6 | import org.I0Itec.zkclient.exception.ZkException; 7 | 8 | import com.opensource.netty.redis.proxy.core.enums.RedisProxyParamType; 9 | import com.opensource.netty.redis.proxy.core.log.impl.LoggerUtils; 10 | import com.opensource.netty.redis.proxy.core.registry.Registry; 11 | import com.opensource.netty.redis.proxy.core.registry.impl.AbstractRegistryFactory; 12 | import com.opensource.netty.redis.proxy.core.url.RedisProxyURL; 13 | 14 | 15 | 16 | /** 17 | * zk 工厂类 18 | * @author liubing 19 | * 20 | */ 21 | 22 | public class ZookeeperRegistryFactory extends AbstractRegistryFactory { 23 | 24 | @Override 25 | protected Registry createRegistry(RedisProxyURL redisProxyURL) { 26 | try { 27 | int timeout = redisProxyURL.getIntParameter(RedisProxyParamType.connectTimeout.getName(), RedisProxyParamType.connectTimeout.getIntValue()); 28 | int sessionTimeout = 29 | redisProxyURL.getIntParameter(RedisProxyParamType.registrySessionTimeout.getName(), 30 | RedisProxyParamType.registrySessionTimeout.getIntValue()); 31 | ZkClient zkClient = new ZkClient(redisProxyURL.getParameter("address"), sessionTimeout, timeout); 32 | return new ZookeeperRegistry(redisProxyURL, zkClient); 33 | } catch (ZkException e) { 34 | LoggerUtils.error("[ZookeeperRegistry] fail to connect zookeeper, cause: " + e.getMessage()); 35 | throw e; 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /nredis-proxy-register/src/main/java/org/I0Itec/zkclient/ContentWatcher.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2010 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.I0Itec.zkclient; 17 | 18 | import java.util.concurrent.locks.Condition; 19 | import java.util.concurrent.locks.Lock; 20 | import java.util.concurrent.locks.ReentrantLock; 21 | 22 | import org.I0Itec.zkclient.exception.ZkNoNodeException; 23 | import org.slf4j.Logger; 24 | import org.slf4j.LoggerFactory; 25 | 26 | /** 27 | * @param 28 | * The data type that is being watched. 29 | */ 30 | public final class ContentWatcher implements IZkDataListener { 31 | 32 | private static final Logger LOG = LoggerFactory.getLogger(ContentWatcher.class); 33 | 34 | private Lock _contentLock = new ReentrantLock(true); 35 | private Condition _contentAvailable = _contentLock.newCondition(); 36 | 37 | private Holder _content; 38 | private String _fileName; 39 | private ZkClient _zkClient; 40 | 41 | public ContentWatcher(ZkClient zkClient, String fileName) { 42 | _fileName = fileName; 43 | _zkClient = zkClient; 44 | } 45 | 46 | public void start() { 47 | _zkClient.subscribeDataChanges(_fileName, this); 48 | readData(); 49 | LOG.debug("Started ContentWatcher"); 50 | } 51 | 52 | @SuppressWarnings("unchecked") 53 | private void readData() { 54 | try { 55 | setContent((T) _zkClient.readData(_fileName)); 56 | } catch (ZkNoNodeException e) { 57 | // ignore if the node has not yet been created 58 | } 59 | } 60 | 61 | public void stop() { 62 | _zkClient.unsubscribeDataChanges(_fileName, this); 63 | } 64 | 65 | public void setContent(T data) { 66 | LOG.debug("Received new data: " + data); 67 | _contentLock.lock(); 68 | try { 69 | _content = new Holder(data); 70 | _contentAvailable.signalAll(); 71 | } finally { 72 | _contentLock.unlock(); 73 | } 74 | } 75 | 76 | @Override 77 | @SuppressWarnings("unchecked") 78 | public void handleDataChange(String dataPath, Object data) { 79 | setContent((T) data); 80 | } 81 | 82 | @Override 83 | public void handleDataDeleted(String dataPath) { 84 | // ignore 85 | } 86 | 87 | public T getContent() throws InterruptedException { 88 | _contentLock.lock(); 89 | try { 90 | while (_content == null) { 91 | _contentAvailable.await(); 92 | } 93 | return _content.get(); 94 | } finally { 95 | _contentLock.unlock(); 96 | } 97 | } 98 | 99 | } 100 | -------------------------------------------------------------------------------- /nredis-proxy-register/src/main/java/org/I0Itec/zkclient/DataUpdater.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2010 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.I0Itec.zkclient; 17 | 18 | /** 19 | * Updates the data of a znode. This is used together with {@link ZkClient#updateDataSerialized(String, DataUpdater)}. 20 | * 21 | * @param 22 | */ 23 | public interface DataUpdater { 24 | 25 | /** 26 | * Updates the current data of a znode. 27 | * 28 | * @param currentData 29 | * The current contents. 30 | * @return the new data that should be written back to ZooKeeper. 31 | */ 32 | public T update(T currentData); 33 | 34 | } 35 | -------------------------------------------------------------------------------- /nredis-proxy-register/src/main/java/org/I0Itec/zkclient/ExceptionUtil.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2010 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.I0Itec.zkclient; 17 | 18 | import org.I0Itec.zkclient.exception.ZkInterruptedException; 19 | 20 | public class ExceptionUtil { 21 | 22 | public static RuntimeException convertToRuntimeException(Throwable e) { 23 | if (e instanceof RuntimeException) { 24 | return (RuntimeException) e; 25 | } 26 | retainInterruptFlag(e); 27 | return new RuntimeException(e); 28 | } 29 | 30 | /** 31 | * This sets the interrupt flag if the catched exception was an {@link InterruptedException}. Catching such an 32 | * exception always clears the interrupt flag. 33 | * 34 | * @param catchedException 35 | * The catched exception. 36 | */ 37 | public static void retainInterruptFlag(Throwable catchedException) { 38 | if (catchedException instanceof InterruptedException) { 39 | Thread.currentThread().interrupt(); 40 | } 41 | } 42 | 43 | public static void rethrowInterruptedException(Throwable e) throws InterruptedException { 44 | if (e instanceof InterruptedException) { 45 | throw (InterruptedException) e; 46 | } 47 | if (e instanceof ZkInterruptedException) { 48 | throw (ZkInterruptedException) e; 49 | } 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /nredis-proxy-register/src/main/java/org/I0Itec/zkclient/Gateway.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2010 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.I0Itec.zkclient; 17 | 18 | public class Gateway { 19 | 20 | private GatewayThread _thread; 21 | private final int _port; 22 | private final int _destinationPort; 23 | 24 | public Gateway(int port, int destinationPort) { 25 | _port = port; 26 | _destinationPort = destinationPort; 27 | } 28 | 29 | public synchronized void start() { 30 | if (_thread != null) { 31 | throw new IllegalStateException("Gateway already running"); 32 | } 33 | _thread = new GatewayThread(_port, _destinationPort); 34 | _thread.start(); 35 | _thread.awaitUp(); 36 | } 37 | 38 | public synchronized void stop() { 39 | if (_thread != null) { 40 | try { 41 | _thread.interruptAndJoin(); 42 | } catch (InterruptedException e) { 43 | Thread.currentThread().interrupt(); 44 | } 45 | _thread = null; 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /nredis-proxy-register/src/main/java/org/I0Itec/zkclient/Holder.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2010 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.I0Itec.zkclient; 17 | 18 | public class Holder { 19 | 20 | private T _value; 21 | 22 | public Holder() { 23 | // do nothing 24 | } 25 | 26 | public Holder(T value) { 27 | _value = value; 28 | } 29 | 30 | public T get() { 31 | return _value; 32 | } 33 | 34 | public void set(T value) { 35 | _value = value; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /nredis-proxy-register/src/main/java/org/I0Itec/zkclient/IDefaultNameSpace.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2010 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.I0Itec.zkclient; 17 | 18 | public interface IDefaultNameSpace { 19 | 20 | /** 21 | * Creates a set of default folder structure within a zookeeper . 22 | * 23 | * @param zkClient 24 | * The zkclient. 25 | */ 26 | public void createDefaultNameSpace(ZkClient zkClient); 27 | } 28 | -------------------------------------------------------------------------------- /nredis-proxy-register/src/main/java/org/I0Itec/zkclient/IZkChildListener.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2010 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.I0Itec.zkclient; 17 | 18 | import java.util.List; 19 | 20 | /** 21 | * An {@link IZkChildListener} can be registered at a {@link ZkClient} for listening on zk child changes for a given 22 | * path. 23 | * 24 | * Node: Also this listener re-subscribes it watch for the path on each zk event (zk watches are one-timers) is is not 25 | * guaranteed that events on the path are missing (see http://zookeeper.wiki.sourceforge.net/ZooKeeperWatches). An 26 | * implementation of this class should take that into account. 27 | * 28 | */ 29 | public interface IZkChildListener { 30 | 31 | /** 32 | * Called when the children of the given path changed. 33 | * 34 | * @param parentPath 35 | * The parent path 36 | * @param currentChilds 37 | * The children or null if the root node (parent path) was deleted. 38 | * @throws Exception 39 | */ 40 | public void handleChildChange(String parentPath, List currentChilds) throws Exception; 41 | } 42 | -------------------------------------------------------------------------------- /nredis-proxy-register/src/main/java/org/I0Itec/zkclient/IZkConnection.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2010 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.I0Itec.zkclient; 17 | 18 | import java.util.List; 19 | import java.util.Map; 20 | 21 | import org.apache.zookeeper.CreateMode; 22 | import org.apache.zookeeper.KeeperException; 23 | import org.apache.zookeeper.Op; 24 | import org.apache.zookeeper.OpResult; 25 | import org.apache.zookeeper.Watcher; 26 | import org.apache.zookeeper.ZooKeeper.States; 27 | import org.apache.zookeeper.data.ACL; 28 | import org.apache.zookeeper.data.Stat; 29 | 30 | public interface IZkConnection { 31 | 32 | public void connect(Watcher watcher); 33 | 34 | void close() throws InterruptedException; 35 | 36 | public String create(String path, byte[] data, CreateMode mode) throws KeeperException, InterruptedException; 37 | 38 | public String create(String path, byte[] data, List acl, CreateMode mode) throws KeeperException, InterruptedException; 39 | 40 | public void delete(String path) throws InterruptedException, KeeperException; 41 | 42 | boolean exists(final String path, final boolean watch) throws KeeperException, InterruptedException; 43 | 44 | List getChildren(final String path, final boolean watch) throws KeeperException, InterruptedException; 45 | 46 | public byte[] readData(String path, Stat stat, boolean watch) throws KeeperException, InterruptedException; 47 | 48 | public void writeData(String path, byte[] data, int expectedVersion) throws KeeperException, InterruptedException; 49 | 50 | public Stat writeDataReturnStat(String path, byte[] data, int expectedVersion) throws KeeperException, InterruptedException; 51 | 52 | public States getZookeeperState(); 53 | 54 | public long getCreateTime(String path) throws KeeperException, InterruptedException; 55 | 56 | public String getServers(); 57 | 58 | public List multi(Iterable ops) throws KeeperException, InterruptedException; 59 | 60 | public void addAuthInfo(String scheme, byte[] auth); 61 | 62 | public void setAcl(final String path, List acl, int version) throws KeeperException, InterruptedException; 63 | 64 | public Map.Entry, Stat> getAcl(final String path) throws KeeperException, InterruptedException; 65 | } -------------------------------------------------------------------------------- /nredis-proxy-register/src/main/java/org/I0Itec/zkclient/IZkDataListener.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2010 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.I0Itec.zkclient; 17 | 18 | /** 19 | * An {@link IZkDataListener} can be registered at a {@link ZkClient} for listening on zk data changes for a given path. 20 | * 21 | * Node: Also this listener re-subscribes it watch for the path on each zk event (zk watches are one-timers) is is not 22 | * guaranteed that events on the path are missing (see http://zookeeper.wiki.sourceforge.net/ZooKeeperWatches). An 23 | * implementation of this class should take that into account. 24 | */ 25 | public interface IZkDataListener { 26 | 27 | public void handleDataChange(String dataPath, Object data) throws Exception; 28 | 29 | public void handleDataDeleted(String dataPath) throws Exception; 30 | 31 | } 32 | -------------------------------------------------------------------------------- /nredis-proxy-register/src/main/java/org/I0Itec/zkclient/IZkStateListener.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2010 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.I0Itec.zkclient; 17 | 18 | import org.apache.zookeeper.Watcher.Event.KeeperState; 19 | 20 | public interface IZkStateListener { 21 | 22 | /** 23 | * Called when the zookeeper connection state has changed. 24 | * 25 | * @param state 26 | * The new state. 27 | * @throws Exception 28 | * On any error. 29 | */ 30 | public void handleStateChanged(KeeperState state) throws Exception; 31 | 32 | /** 33 | * Called after the zookeeper session has expired and a new session has been created. You would have to re-create 34 | * any ephemeral nodes here. 35 | * 36 | * @throws Exception 37 | * On any error. 38 | */ 39 | public void handleNewSession() throws Exception; 40 | 41 | /** 42 | * Called when a session cannot be re-established. This should be used to implement connection 43 | * failure handling e.g. retry to connect or pass the error up 44 | * 45 | * @param error 46 | * The error that prevents a session from being established 47 | * @throws Exception 48 | * On any error. 49 | */ 50 | public void handleSessionEstablishmentError(final Throwable error) throws Exception; 51 | 52 | } 53 | -------------------------------------------------------------------------------- /nredis-proxy-register/src/main/java/org/I0Itec/zkclient/ZkLock.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2010 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.I0Itec.zkclient; 17 | 18 | import java.util.concurrent.locks.Condition; 19 | import java.util.concurrent.locks.ReentrantLock; 20 | 21 | public class ZkLock extends ReentrantLock { 22 | 23 | private static final long serialVersionUID = 1L; 24 | 25 | private Condition _dataChangedCondition = newCondition(); 26 | private Condition _stateChangedCondition = newCondition(); 27 | private Condition _zNodeEventCondition = newCondition(); 28 | 29 | /** 30 | * This condition will be signaled if a zookeeper event was processed and the event contains a data/child change. 31 | * 32 | * @return the condition. 33 | */ 34 | public Condition getDataChangedCondition() { 35 | return _dataChangedCondition; 36 | } 37 | 38 | /** 39 | * This condition will be signaled if a zookeeper event was processed and the event contains a state change 40 | * (connected, disconnected, session expired, etc ...). 41 | * 42 | * @return the condition. 43 | */ 44 | public Condition getStateChangedCondition() { 45 | return _stateChangedCondition; 46 | } 47 | 48 | /** 49 | * This condition will be signaled if any znode related zookeeper event was received. 50 | * 51 | * @return the condition. 52 | */ 53 | public Condition getZNodeEventCondition() { 54 | return _zNodeEventCondition; 55 | } 56 | } -------------------------------------------------------------------------------- /nredis-proxy-register/src/main/java/org/I0Itec/zkclient/exception/ZkBadVersionException.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2010 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.I0Itec.zkclient.exception; 17 | 18 | import org.apache.zookeeper.KeeperException; 19 | 20 | public class ZkBadVersionException extends ZkException { 21 | 22 | private static final long serialVersionUID = 1L; 23 | 24 | public ZkBadVersionException() { 25 | super(); 26 | } 27 | 28 | public ZkBadVersionException(KeeperException cause) { 29 | super(cause); 30 | } 31 | 32 | public ZkBadVersionException(String message, KeeperException cause) { 33 | super(message, cause); 34 | } 35 | 36 | public ZkBadVersionException(String message) { 37 | super(message); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /nredis-proxy-register/src/main/java/org/I0Itec/zkclient/exception/ZkException.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2010 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.I0Itec.zkclient.exception; 17 | 18 | import org.apache.zookeeper.KeeperException; 19 | 20 | public class ZkException extends RuntimeException { 21 | 22 | private static final long serialVersionUID = 1L; 23 | 24 | public ZkException() { 25 | super(); 26 | } 27 | 28 | public ZkException(String message, Throwable cause) { 29 | super(message, cause); 30 | } 31 | 32 | public ZkException(String message) { 33 | super(message); 34 | } 35 | 36 | public ZkException(Throwable cause) { 37 | super(cause); 38 | } 39 | 40 | public static ZkException create(KeeperException e) { 41 | switch (e.code()) { 42 | // case DATAINCONSISTENCY: 43 | // return new DataInconsistencyException(); 44 | // case CONNECTIONLOSS: 45 | // return new ConnectionLossException(); 46 | case NONODE: 47 | return new ZkNoNodeException(e); 48 | // case NOAUTH: 49 | // return new ZkNoAuthException(); 50 | case BADVERSION: 51 | return new ZkBadVersionException(e); 52 | // case NOCHILDRENFOREPHEMERALS: 53 | // return new NoChildrenForEphemeralsException(); 54 | case NODEEXISTS: 55 | return new ZkNodeExistsException(e); 56 | // case INVALIDACL: 57 | // return new ZkInvalidACLException(); 58 | // case AUTHFAILED: 59 | // return new AuthFailedException(); 60 | // case NOTEMPTY: 61 | // return new NotEmptyException(); 62 | // case SESSIONEXPIRED: 63 | // return new SessionExpiredException(); 64 | // case INVALIDCALLBACK: 65 | // return new InvalidCallbackException(); 66 | 67 | default: 68 | return new ZkException(e); 69 | } 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /nredis-proxy-register/src/main/java/org/I0Itec/zkclient/exception/ZkInterruptedException.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2010 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.I0Itec.zkclient.exception; 17 | 18 | public class ZkInterruptedException extends ZkException { 19 | 20 | private static final long serialVersionUID = 1L; 21 | 22 | public ZkInterruptedException(InterruptedException e) { 23 | super(e); 24 | Thread.currentThread().interrupt(); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /nredis-proxy-register/src/main/java/org/I0Itec/zkclient/exception/ZkMarshallingError.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2010 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.I0Itec.zkclient.exception; 17 | 18 | public class ZkMarshallingError extends ZkException { 19 | 20 | private static final long serialVersionUID = 1L; 21 | 22 | public ZkMarshallingError() { 23 | super(); 24 | } 25 | 26 | public ZkMarshallingError(Throwable cause) { 27 | super(cause); 28 | } 29 | 30 | public ZkMarshallingError(String message, Throwable cause) { 31 | super(message, cause); 32 | } 33 | 34 | public ZkMarshallingError(String message) { 35 | super(message); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /nredis-proxy-register/src/main/java/org/I0Itec/zkclient/exception/ZkNoNodeException.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2010 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.I0Itec.zkclient.exception; 17 | 18 | import org.apache.zookeeper.KeeperException; 19 | 20 | public class ZkNoNodeException extends ZkException { 21 | 22 | private static final long serialVersionUID = 1L; 23 | 24 | public ZkNoNodeException() { 25 | super(); 26 | } 27 | 28 | public ZkNoNodeException(KeeperException cause) { 29 | super(cause); 30 | } 31 | 32 | public ZkNoNodeException(String message, KeeperException cause) { 33 | super(message, cause); 34 | } 35 | 36 | public ZkNoNodeException(String message) { 37 | super(message); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /nredis-proxy-register/src/main/java/org/I0Itec/zkclient/exception/ZkNodeExistsException.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2010 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.I0Itec.zkclient.exception; 17 | 18 | import org.apache.zookeeper.KeeperException; 19 | 20 | public class ZkNodeExistsException extends ZkException { 21 | 22 | private static final long serialVersionUID = 1L; 23 | 24 | public ZkNodeExistsException() { 25 | super(); 26 | } 27 | 28 | public ZkNodeExistsException(KeeperException cause) { 29 | super(cause); 30 | } 31 | 32 | public ZkNodeExistsException(String message, KeeperException cause) { 33 | super(message, cause); 34 | } 35 | 36 | public ZkNodeExistsException(String message) { 37 | super(message); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /nredis-proxy-register/src/main/java/org/I0Itec/zkclient/exception/ZkTimeoutException.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2010 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.I0Itec.zkclient.exception; 17 | 18 | public class ZkTimeoutException extends ZkException { 19 | 20 | private static final long serialVersionUID = 1L; 21 | 22 | public ZkTimeoutException() { 23 | super(); 24 | } 25 | 26 | public ZkTimeoutException(String message, Throwable cause) { 27 | super(message, cause); 28 | } 29 | 30 | public ZkTimeoutException(String message) { 31 | super(message); 32 | } 33 | 34 | public ZkTimeoutException(Throwable cause) { 35 | super(cause); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /nredis-proxy-register/src/main/java/org/I0Itec/zkclient/serialize/BytesPushThroughSerializer.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2010 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.I0Itec.zkclient.serialize; 17 | 18 | import org.I0Itec.zkclient.exception.ZkMarshallingError; 19 | 20 | /** 21 | * A {@link ZkSerializer} which simply passes byte arrays to zk and back. 22 | */ 23 | public class BytesPushThroughSerializer implements ZkSerializer { 24 | 25 | @Override 26 | public Object deserialize(byte[] bytes) throws ZkMarshallingError { 27 | return bytes; 28 | } 29 | 30 | @Override 31 | public byte[] serialize(Object bytes) throws ZkMarshallingError { 32 | return (byte[]) bytes; 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /nredis-proxy-register/src/main/java/org/I0Itec/zkclient/serialize/SerializableSerializer.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2010 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.I0Itec.zkclient.serialize; 17 | 18 | import java.io.ByteArrayInputStream; 19 | import java.io.ByteArrayOutputStream; 20 | import java.io.IOException; 21 | import java.io.ObjectInputStream; 22 | import java.io.ObjectOutputStream; 23 | 24 | import org.I0Itec.zkclient.exception.ZkMarshallingError; 25 | 26 | public class SerializableSerializer implements ZkSerializer { 27 | 28 | @Override 29 | public Object deserialize(byte[] bytes) throws ZkMarshallingError { 30 | try (ObjectInputStream inputStream = new TcclAwareObjectIputStream(new ByteArrayInputStream(bytes));) { 31 | Object object = inputStream.readObject(); 32 | return object; 33 | } catch (ClassNotFoundException e) { 34 | throw new ZkMarshallingError("Unable to find object class.", e); 35 | } catch (IOException e) { 36 | throw new ZkMarshallingError(e); 37 | } 38 | } 39 | 40 | @Override 41 | public byte[] serialize(Object serializable) throws ZkMarshallingError { 42 | try (ByteArrayOutputStream byteArrayOS = new ByteArrayOutputStream(); 43 | ObjectOutputStream stream = new ObjectOutputStream(byteArrayOS);) { 44 | stream.writeObject(serializable); 45 | return byteArrayOS.toByteArray(); 46 | } catch (IOException e) { 47 | throw new ZkMarshallingError(e); 48 | } 49 | } 50 | 51 | } 52 | -------------------------------------------------------------------------------- /nredis-proxy-register/src/main/java/org/I0Itec/zkclient/serialize/TcclAwareObjectIputStream.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2010 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.I0Itec.zkclient.serialize; 17 | 18 | import java.io.IOException; 19 | import java.io.InputStream; 20 | import java.io.ObjectInputStream; 21 | import java.io.ObjectStreamClass; 22 | import java.lang.reflect.Proxy; 23 | 24 | /** 25 | * An ObjectInputStream that is aware of the TCCL. 26 | */ 27 | public class TcclAwareObjectIputStream extends ObjectInputStream { 28 | 29 | public TcclAwareObjectIputStream(InputStream in) throws IOException { 30 | super(in); 31 | } 32 | 33 | /** 34 | * Load the local class equivalent of the specified stream class 35 | * description. 36 | * Uses the current class {@link ClassLoader} and falls back to the {@link Thread} context {@link ClassLoader}. 37 | */ 38 | @Override 39 | protected Class resolveClass(ObjectStreamClass classDesc) throws IOException, ClassNotFoundException { 40 | try { 41 | return getClass().getClassLoader().loadClass(classDesc.getName()); 42 | } catch (ClassNotFoundException ex) { 43 | ClassLoader tccl = Thread.currentThread().getContextClassLoader(); 44 | if (tccl != null) { 45 | return tccl.loadClass(classDesc.getName()); 46 | } else { 47 | throw ex; 48 | } 49 | } 50 | } 51 | 52 | /** 53 | * Returns a proxy class that implements the interfaces named in a proxy 54 | * class descriptor; subclasses may implement this method to read custom 55 | * data from the stream along with the descriptors for dynamic proxy 56 | * classes, allowing them to use an alternate loading mechanism for the 57 | * interfaces and the proxy class. 58 | * 59 | * For each interface uses the current class {@link ClassLoader} and falls back to the {@link Thread} context {@link ClassLoader}. 60 | */ 61 | @Override 62 | protected Class resolveProxyClass(String[] interfaces) throws IOException, ClassNotFoundException { 63 | ClassLoader cl = getClass().getClassLoader(); 64 | Class[] cinterfaces = new Class[interfaces.length]; 65 | 66 | for (int i = 0; i < interfaces.length; i++) { 67 | try { 68 | cinterfaces[i] = cl.loadClass(interfaces[i]); 69 | } catch (ClassNotFoundException ex) { 70 | ClassLoader tccl = Thread.currentThread().getContextClassLoader(); 71 | if (tccl != null) { 72 | return tccl.loadClass(interfaces[i]); 73 | } else { 74 | throw ex; 75 | } 76 | } 77 | } 78 | try { 79 | return Proxy.getProxyClass(cinterfaces[0].getClassLoader(), cinterfaces); 80 | } catch (IllegalArgumentException e) { 81 | throw new ClassNotFoundException(null, e); 82 | } 83 | } 84 | 85 | } 86 | -------------------------------------------------------------------------------- /nredis-proxy-register/src/main/java/org/I0Itec/zkclient/serialize/ZkSerializer.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2010 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.I0Itec.zkclient.serialize; 17 | 18 | import org.I0Itec.zkclient.exception.ZkMarshallingError; 19 | 20 | /** 21 | * Zookeeper is able to store data in form of byte arrays. This interfacte is a bridge between those byte-array format 22 | * and higher level objects. 23 | * 24 | * @see BytesPushThroughSerializer 25 | * @see SerializableSerializer 26 | */ 27 | public interface ZkSerializer { 28 | 29 | public byte[] serialize(Object data) throws ZkMarshallingError; 30 | 31 | public Object deserialize(byte[] bytes) throws ZkMarshallingError; 32 | } 33 | -------------------------------------------------------------------------------- /nredis-proxy-register/src/main/java/org/I0Itec/zkclient/util/ZkPathUtil.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2010 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.I0Itec.zkclient.util; 17 | 18 | import java.util.List; 19 | 20 | import org.I0Itec.zkclient.ZkClient; 21 | 22 | public class ZkPathUtil { 23 | 24 | public static String leadingZeros(long number, int numberOfLeadingZeros) { 25 | return String.format("%0" + numberOfLeadingZeros + "d", number); 26 | } 27 | 28 | public static String toString(ZkClient zkClient) { 29 | return toString(zkClient, "/", PathFilter.ALL); 30 | } 31 | 32 | public static String toString(ZkClient zkClient, String startPath, PathFilter pathFilter) { 33 | final int level = 1; 34 | final StringBuilder builder = new StringBuilder("+ (" + startPath + ")"); 35 | builder.append("\n"); 36 | addChildrenToStringBuilder(zkClient, pathFilter, level, builder, startPath); 37 | return builder.toString(); 38 | } 39 | 40 | private static void addChildrenToStringBuilder(ZkClient zkClient, PathFilter pathFilter, final int level, final StringBuilder builder, final String startPath) { 41 | final List children = zkClient.getChildren(startPath); 42 | for (final String node : children) { 43 | String nestedPath; 44 | if (startPath.endsWith("/")) { 45 | nestedPath = startPath + node; 46 | } else { 47 | nestedPath = startPath + "/" + node; 48 | } 49 | if (pathFilter.showChilds(nestedPath)) { 50 | builder.append(getSpaces(level - 1) + "'-" + "+" + node + "\n"); 51 | addChildrenToStringBuilder(zkClient, pathFilter, level + 1, builder, nestedPath); 52 | } else { 53 | builder.append(getSpaces(level - 1) + "'-" + "-" + node + " (contents hidden)\n"); 54 | } 55 | } 56 | } 57 | 58 | private static String getSpaces(final int level) { 59 | String s = ""; 60 | for (int i = 0; i < level; i++) { 61 | s += " "; 62 | } 63 | return s; 64 | } 65 | 66 | public static interface PathFilter { 67 | 68 | public static PathFilter ALL = new PathFilter() { 69 | 70 | @Override 71 | public boolean showChilds(String path) { 72 | return true; 73 | } 74 | }; 75 | 76 | boolean showChilds(String path); 77 | } 78 | 79 | } 80 | -------------------------------------------------------------------------------- /nredis-proxy-sample/.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | -------------------------------------------------------------------------------- /nredis-proxy-sample/.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | -------------------------------------------------------------------------------- /nredis-proxy-sample/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | nredis-proxy-sample 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.jdt.core.javabuilder 10 | 11 | 12 | 13 | 14 | org.eclipse.m2e.core.maven2Builder 15 | 16 | 17 | 18 | 19 | 20 | org.eclipse.jdt.core.javanature 21 | org.eclipse.m2e.core.maven2Nature 22 | 23 | 24 | -------------------------------------------------------------------------------- /nredis-proxy-sample/.settings/org.eclipse.core.resources.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | encoding//src/main/java=UTF-8 3 | encoding//src/main/resources=UTF-8 4 | encoding//src/test/java=UTF-8 5 | encoding/=UTF-8 6 | -------------------------------------------------------------------------------- /nredis-proxy-sample/.settings/org.eclipse.jdt.core.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.7 3 | org.eclipse.jdt.core.compiler.compliance=1.7 4 | org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning 5 | org.eclipse.jdt.core.compiler.source=1.7 6 | -------------------------------------------------------------------------------- /nredis-proxy-sample/.settings/org.eclipse.m2e.core.prefs: -------------------------------------------------------------------------------- 1 | activeProfiles= 2 | eclipse.preferences.version=1 3 | resolveWorkspaceProjects=true 4 | version=1 5 | -------------------------------------------------------------------------------- /nredis-proxy-sample/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.opensource 7 | nredis-proxy 8 | 1.0 9 | 10 | com.opensource 11 | nredis-proxy-sample 12 | 1.0 13 | nredis-proxy-sample 14 | http://maven.apache.org 15 | 16 | UTF-8 17 | 18 | 19 | 20 | junit 21 | junit 22 | test 23 | 24 | 25 | com.opensource 26 | nredis-proxy-spring 27 | 28 | 29 | org.slf4j 30 | slf4j-api 31 | 1.5.8 32 | 33 | 34 | 35 | org.slf4j 36 | slf4j-log4j12 37 | 1.5.8 38 | 39 | 40 | 41 | log4j 42 | log4j 43 | 1.2.14 44 | 45 | 46 | redis.clients 47 | jedis 48 | 2.7.3 49 | 50 | 51 | org.springframework 52 | spring-context 53 | 4.1.7.RELEASE 54 | 55 | 56 | 57 | 58 | 59 | org.apache.maven.plugins 60 | maven-assembly-plugin 61 | 2.4 62 | 63 | false 64 | 65 | src/main/assembly/assembly.xml 66 | 67 | 68 | 69 | 70 | make-assembly 71 | package 72 | 73 | single 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | -------------------------------------------------------------------------------- /nredis-proxy-sample/src/main/assembly/assembly.xml: -------------------------------------------------------------------------------- 1 | 2 | package 3 | 4 | dir 5 | 6 | false 7 | 8 | 9 | true 10 | lib 11 | 12 | 13 | 14 | 15 | true 16 | src/main/resources 17 | /config 18 | 19 | 20 | 21 | 22 | src/main/deploy/single.sh 23 | /bin 24 | 25 | 26 | -------------------------------------------------------------------------------- /nredis-proxy-sample/src/main/deploy/package-dependency.properties: -------------------------------------------------------------------------------- 1 | settlement-base 2 | settlement-dao 3 | settlement-service -------------------------------------------------------------------------------- /nredis-proxy-sample/src/main/deploy/single.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | #取当前目录 4 | BASE_PATH=`cd "$(dirname "$0")"; pwd` 5 | 6 | #设置java运行参数 7 | DEFAULT_JAVA_OPTS=" -server -Xmx1g -Xms1g -Xmn256m -XX:PermSize=128m -Xss256k -XX:+DisableExplicitGC -XX:+UseConcMarkSweepGC -XX:+CMSParallelRemarkEnabled -XX:+UseCMSCompactAtFullCollection -XX:LargePageSizeInBytes=128m -XX:+UseFastAccessorMethods -XX:+UseCMSInitiatingOccupancyOnly -XX:CMSInitiatingOccupancyFraction=70 -Dfile.encoding=utf-8 " 8 | 9 | 10 | #引入外部参数配置文件: 11 | SHELL_PARAMS="$BASE_PATH/params.conf" 12 | if [ -f "$SHELL_PARAMS" ]; then 13 | . $SHELL_PARAMS 14 | fi 15 | 16 | #定义变量: 17 | APP_PATH=${APP_PATH:-`dirname "$BASE_PATH"`} 18 | LOG_PATH=${APP_PATH}/logs 19 | if [ ! -d $LOG_PATH ]; then 20 | mkdir -p $LOG_PATH 21 | fi 22 | CLASS_PATH=${CLASS_PATH:-$APP_PATH/config:$APP_PATH/lib/*} 23 | CONSOLE_LOG=${LOG_PATH}/timer_console.log 24 | JAVA_OPTS=${JAVA_OPTS:-$DEFAULT_JAVA_OPTS} 25 | MAIN_CLASS=${MAIN_CLASS:-"com.opensource.netty.redis.proxy.sample.RedisProxyServerBootStrap"} 26 | 27 | 28 | exist(){ 29 | if test $( pgrep -f "$MAIN_CLASS $APP_PATH" | wc -l ) -eq 0 30 | then 31 | return 1 32 | else 33 | return 0 34 | fi 35 | } 36 | 37 | start(){ 38 | if exist; then 39 | echo "Timer is already running." 40 | exit 1 41 | else 42 | cd $APP_PATH 43 | echo "nohup java $JAVA_OPTS -cp $CLASS_PATH $MAIN_CLASS $APP_PATH 2> /dev/null & " 44 | nohup java $JAVA_OPTS -cp $CLASS_PATH $MAIN_CLASS $APP_PATH > ${CONSOLE_LOG} 2>&1 & 45 | echo "Timer is started." 46 | fi 47 | } 48 | 49 | stop(){ 50 | runningPID=`pgrep -f "$MAIN_CLASS $APP_PATH"` 51 | if [ "$runningPID" ]; then 52 | echo "Timer pid: $runningPID" 53 | count=0 54 | kwait=5 55 | echo "Timer is stopping, please wait..." 56 | kill -15 $runningPID 57 | until [ `ps --pid $runningPID 2> /dev/null | grep -c $runningPID 2> /dev/null` -eq '0' ] || [ $count -gt $kwait ] 58 | do 59 | sleep 1 60 | let count=$count+1; 61 | done 62 | 63 | if [ $count -gt $kwait ]; then 64 | kill -9 $runningPID 65 | fi 66 | clear 67 | echo "Timer is stopped." 68 | else 69 | echo "Timer has not been started." 70 | fi 71 | } 72 | 73 | check(){ 74 | if exist; then 75 | echo "Timer is alive." 76 | exit 0 77 | else 78 | echo "Timer is dead." 79 | exit -1 80 | fi 81 | } 82 | 83 | restart(){ 84 | stop 85 | start 86 | } 87 | 88 | case "$1" in 89 | 90 | start) 91 | start 92 | ;; 93 | stop) 94 | stop 95 | ;; 96 | restart) 97 | restart 98 | ;; 99 | check) 100 | check 101 | ;; 102 | *) 103 | echo "available operations: [start|stop|restart|check]" 104 | exit 1 105 | ;; 106 | esac -------------------------------------------------------------------------------- /nredis-proxy-sample/src/main/java/com/opensource/netty/redis/proxy/sample/ClassRoom.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package com.opensource.netty.redis.proxy.sample; 5 | 6 | import java.io.Serializable; 7 | 8 | /** 9 | * @author liubing 10 | * 11 | */ 12 | public class ClassRoom implements Serializable { 13 | 14 | /** 15 | * 16 | */ 17 | private static final long serialVersionUID = 3045043390218727347L; 18 | 19 | private String name; 20 | 21 | private String height; 22 | 23 | private Integer weight; 24 | 25 | /** 26 | * @return the name 27 | */ 28 | public String getName() { 29 | return name; 30 | } 31 | 32 | /** 33 | * @param name the name to set 34 | */ 35 | public void setName(String name) { 36 | this.name = name; 37 | } 38 | 39 | /** 40 | * @return the height 41 | */ 42 | public String getHeight() { 43 | return height; 44 | } 45 | 46 | /** 47 | * @param height the height to set 48 | */ 49 | public void setHeight(String height) { 50 | this.height = height; 51 | } 52 | 53 | /** 54 | * @return the weight 55 | */ 56 | public Integer getWeight() { 57 | return weight; 58 | } 59 | 60 | /** 61 | * @param weight the weight to set 62 | */ 63 | public void setWeight(Integer weight) { 64 | this.weight = weight; 65 | } 66 | 67 | /** 68 | * @param name 69 | * @param height 70 | * @param weight 71 | */ 72 | public ClassRoom(String name, String height, Integer weight) { 73 | super(); 74 | this.name = name; 75 | this.height = height; 76 | this.weight = weight; 77 | } 78 | 79 | 80 | } 81 | -------------------------------------------------------------------------------- /nredis-proxy-sample/src/main/java/com/opensource/netty/redis/proxy/sample/RedisClientDemo.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package com.opensource.netty.redis.proxy.sample; 5 | 6 | import com.alibaba.fastjson.JSONObject; 7 | 8 | import redis.clients.jedis.Jedis; 9 | 10 | /** 11 | * @author liubing 12 | * 13 | */ 14 | public class RedisClientDemo { 15 | 16 | /** 17 | * @param args 18 | */ 19 | public static void main(String[] args) { 20 | 21 | Jedis redis = new Jedis ("127.0.0.1",6379); 22 | System.out.println(redis.get("classRoom")); 23 | ClassRoom classRoom=new ClassRoom("liubing", "168", 120); 24 | redis.set("classRoom", JSONObject.toJSONString(classRoom)); 25 | //redis.expire("classRoom", 100); 26 | //redis.close(); 27 | // redis.slaveofNoOne(); 28 | //System.out.println(redis.get("name")); 29 | 30 | 31 | //redis.set("name", "liubing1"); 32 | //redis.expire("name", 10); 33 | 34 | // for(int z=0;z<5;z++){ 35 | // long startTime=System.currentTimeMillis(); 36 | // for(int j=0;j<1000;j++){ 37 | // for(int i=0;i<100;i++){ 38 | // //System.out.println(i); 39 | // redis.get("name"); 40 | // //redis.set("name", "liubing1"); 41 | // } 42 | // } 43 | // long endTime=System.currentTimeMillis(); 44 | // System.out.println("完成时间:"+(endTime-startTime)); 45 | // } 46 | 47 | } 48 | 49 | } 50 | -------------------------------------------------------------------------------- /nredis-proxy-sample/src/main/java/com/opensource/netty/redis/proxy/sample/RedisProxyServerBootStrap.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package com.opensource.netty.redis.proxy.sample; 5 | 6 | import org.springframework.context.support.ClassPathXmlApplicationContext; 7 | 8 | /** 9 | * @author liubing 10 | * 11 | */ 12 | public class RedisProxyServerBootStrap { 13 | 14 | public static void main(String[] args) { 15 | new ClassPathXmlApplicationContext(new String[] {"classpath*:redisProxy.xml"}); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /nredis-proxy-sample/src/main/java/com/opensource/netty/redis/proxy/sample/ShortUrl.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package com.opensource.netty.redis.proxy.sample; 5 | 6 | /** 7 | * @author liubing 8 | * 9 | */ 10 | public class ShortUrl { 11 | 12 | public static final String ALPHABET = "23456789bcdfghjkmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ-_"; 13 | public static final int BASE = ALPHABET.length(); 14 | 15 | public static String encode(int num) { 16 | StringBuilder str = new StringBuilder(); 17 | while (num > 0) { 18 | str.insert(0, ALPHABET.charAt(num % BASE)); 19 | num = num / BASE; 20 | } 21 | return str.toString(); 22 | } 23 | 24 | public static int decode(String str) { 25 | int num = 0; 26 | for (int i = 0; i < str.length(); i++) { 27 | num = num * BASE + ALPHABET.indexOf(str.charAt(i)); 28 | } 29 | return num; 30 | } 31 | 32 | public static void main(String[] args) { 33 | System.out.println(ShortUrl.encode(1148665819)); 34 | System.out.println(ShortUrl.decode("baidu")); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /nredis-proxy-sample/src/main/resources/log4j.properties: -------------------------------------------------------------------------------- 1 | log4j.rootLogger=info,hedis,file 2 | 3 | log4j.appender.hedis=org.apache.log4j.ConsoleAppender 4 | log4j.appender.hedis.layout=org.apache.log4j.PatternLayout 5 | log4j.appender.hedis.layout.ConversionPattern=%d{yyyy-MM-dd HH\:mm\:ss,SSS} %-5p %c{1} %x - %m%n 6 | 7 | log4j.appender.file=org.apache.log4j.RollingFileAppender 8 | log4j.appender.file.File=./log/hedis.log 9 | log4j.appender.file.MaxFileSize=5120KB 10 | log4j.appender.file.MaxBackupIndex=10 11 | log4j.appender.file.layout=org.apache.log4j.PatternLayout 12 | log4j.appender.file.layout.ConversionPattern=[VAMS][%d] %p | %m | [%t] %C.%M(%L)%n -------------------------------------------------------------------------------- /nredis-proxy-sample/src/main/resources/redisProxy.xml: -------------------------------------------------------------------------------- 1 | 2 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /nredis-proxy-sample/src/test/java/org/nredis/proxy/sample/AppTest.java: -------------------------------------------------------------------------------- 1 | package org.nredis.proxy.sample; 2 | 3 | import junit.framework.Test; 4 | import junit.framework.TestCase; 5 | import junit.framework.TestSuite; 6 | 7 | /** 8 | * Unit test for simple App. 9 | */ 10 | public class AppTest 11 | extends TestCase 12 | { 13 | /** 14 | * Create the test case 15 | * 16 | * @param testName name of the test case 17 | */ 18 | public AppTest( String testName ) 19 | { 20 | super( testName ); 21 | } 22 | 23 | /** 24 | * @return the suite of tests being tested 25 | */ 26 | public static Test suite() 27 | { 28 | return new TestSuite( AppTest.class ); 29 | } 30 | 31 | /** 32 | * Rigourous Test :-) 33 | */ 34 | public void testApp() 35 | { 36 | assertTrue( true ); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /nredis-proxy-spring/.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /nredis-proxy-spring/.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | -------------------------------------------------------------------------------- /nredis-proxy-spring/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | nredis-proxy-spring 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.jdt.core.javabuilder 10 | 11 | 12 | 13 | 14 | org.eclipse.m2e.core.maven2Builder 15 | 16 | 17 | 18 | 19 | 20 | org.eclipse.jdt.core.javanature 21 | org.eclipse.m2e.core.maven2Nature 22 | 23 | 24 | -------------------------------------------------------------------------------- /nredis-proxy-spring/.settings/org.eclipse.core.resources.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | encoding//src/main/java=UTF-8 3 | encoding//src/main/resources=UTF-8 4 | encoding/=UTF-8 5 | -------------------------------------------------------------------------------- /nredis-proxy-spring/.settings/org.eclipse.jdt.core.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.7 3 | org.eclipse.jdt.core.compiler.compliance=1.7 4 | org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning 5 | org.eclipse.jdt.core.compiler.source=1.7 6 | -------------------------------------------------------------------------------- /nredis-proxy-spring/.settings/org.eclipse.m2e.core.prefs: -------------------------------------------------------------------------------- 1 | activeProfiles= 2 | eclipse.preferences.version=1 3 | resolveWorkspaceProjects=true 4 | version=1 5 | -------------------------------------------------------------------------------- /nredis-proxy-spring/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.opensource 7 | nredis-proxy 8 | 1.0 9 | 10 | com.opensource 11 | nredis-proxy-spring 12 | 1.0 13 | nredis-proxy-spring 14 | http://maven.apache.org 15 | 16 | UTF-8 17 | 18 | 19 | 20 | junit 21 | junit 22 | test 23 | 24 | 25 | com.opensource 26 | nredis-proxy-net 27 | 28 | 29 | com.opensource 30 | nredis-proxy-register 31 | 32 | 33 | org.springframework 34 | spring-context 35 | 4.1.7.RELEASE 36 | provided 37 | 38 | 39 | 40 | -------------------------------------------------------------------------------- /nredis-proxy-spring/src/main/java/com/opensource/netty/redis/proxy/spring/handler/RedisProxyHandlerSupport.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package com.opensource.netty.redis.proxy.spring.handler; 5 | 6 | import org.springframework.beans.factory.xml.NamespaceHandlerSupport; 7 | 8 | import com.opensource.netty.redis.proxy.spring.schema.RedisProxyNodeParser; 9 | import com.opensource.netty.redis.proxy.spring.schema.support.RedisProxyConstant; 10 | 11 | 12 | /** 13 | * @author liubing 14 | * 15 | */ 16 | public class RedisProxyHandlerSupport extends NamespaceHandlerSupport { 17 | 18 | /* (non-Javadoc) 19 | * @see org.springframework.beans.factory.xml.NamespaceHandler#init() 20 | */ 21 | @Override 22 | public void init() { 23 | // registerBeanDefinitionParser(RedisProxyConstant.REDISPROXYCLUSTER, new RedisProxyClusterParser()); 24 | // registerBeanDefinitionParser(RedisProxyConstant.REDISPROXYMASTER, new RedisProxyMasterParser()); 25 | registerBeanDefinitionParser(RedisProxyConstant.REDISPROXYNODE, new RedisProxyNodeParser()); 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /nredis-proxy-spring/src/main/java/com/opensource/netty/redis/proxy/spring/schema/support/RedisProxyCluster.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package com.opensource.netty.redis.proxy.spring.schema.support; 5 | 6 | import java.io.Serializable; 7 | 8 | /** 9 | * @author liubing 10 | * 11 | */ 12 | public class RedisProxyCluster implements Serializable { 13 | 14 | /** 15 | * 16 | */ 17 | private static final long serialVersionUID = 2087897700756695413L; 18 | 19 | private String host;//主机名 20 | 21 | private int port;//端口号 22 | 23 | private int timeout;//超时时间 24 | 25 | private int maxActiveConnection;//最大活动连接数 26 | 27 | private int maxIdleConnection;//最大 空闲连接数 28 | 29 | private int minConnection;//最小连接数 30 | 31 | private int weight=1;//默认权重比例为1 32 | 33 | 34 | /** 35 | * @return the host 36 | */ 37 | public String getHost() { 38 | return host; 39 | } 40 | 41 | /** 42 | * @param host the host to set 43 | */ 44 | public void setHost(String host) { 45 | this.host = host; 46 | } 47 | 48 | /** 49 | * @return the port 50 | */ 51 | public int getPort() { 52 | return port; 53 | } 54 | 55 | /** 56 | * @param port the port to set 57 | */ 58 | public void setPort(int port) { 59 | this.port = port; 60 | } 61 | 62 | /** 63 | * @return the timeout 64 | */ 65 | public int getTimeout() { 66 | return timeout; 67 | } 68 | 69 | /** 70 | * @param timeout the timeout to set 71 | */ 72 | public void setTimeout(int timeout) { 73 | this.timeout = timeout; 74 | } 75 | 76 | /** 77 | * @return the maxActiveConnection 78 | */ 79 | public int getMaxActiveConnection() { 80 | return maxActiveConnection; 81 | } 82 | 83 | /** 84 | * @param maxActiveConnection the maxActiveConnection to set 85 | */ 86 | public void setMaxActiveConnection(int maxActiveConnection) { 87 | this.maxActiveConnection = maxActiveConnection; 88 | } 89 | 90 | /** 91 | * @return the maxIdleConnection 92 | */ 93 | public int getMaxIdleConnection() { 94 | return maxIdleConnection; 95 | } 96 | 97 | /** 98 | * @param maxIdleConnection the maxIdleConnection to set 99 | */ 100 | public void setMaxIdleConnection(int maxIdleConnection) { 101 | this.maxIdleConnection = maxIdleConnection; 102 | } 103 | 104 | /** 105 | * @return the minConnection 106 | */ 107 | public int getMinConnection() { 108 | return minConnection; 109 | } 110 | 111 | /** 112 | * @param minConnection the minConnection to set 113 | */ 114 | public void setMinConnection(int minConnection) { 115 | this.minConnection = minConnection; 116 | } 117 | 118 | /** 119 | * @return the weight 120 | */ 121 | public int getWeight() { 122 | return weight; 123 | } 124 | 125 | /** 126 | * @param weight the weight to set 127 | */ 128 | public void setWeight(int weight) { 129 | this.weight = weight; 130 | } 131 | 132 | /** 133 | * @return the key 134 | */ 135 | public String getKey() { 136 | StringBuilder stringBuilder=new StringBuilder(); 137 | stringBuilder.append(host).append("-").append(port); 138 | return stringBuilder.toString(); 139 | } 140 | 141 | 142 | } 143 | -------------------------------------------------------------------------------- /nredis-proxy-spring/src/main/java/com/opensource/netty/redis/proxy/spring/schema/support/RedisProxyConstant.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package com.opensource.netty.redis.proxy.spring.schema.support; 5 | 6 | /** 7 | * @author liubing 8 | * 9 | */ 10 | public class RedisProxyConstant { 11 | 12 | public static final String HOST = "host"; 13 | 14 | public static final String PORT="port"; 15 | 16 | public static final String TIMEOUT="timeout"; 17 | 18 | public static final String MAXACTIVECONNECTION="maxActiveConnection"; 19 | 20 | public static final String MAXIDLECONNECTION="maxIdleConnection"; 21 | 22 | public static final String MINCONNECTION="minConnection"; 23 | 24 | public static final String WEIGHT="weight"; 25 | 26 | public static final String REDISPROXYCLUSTERS="redisProxyClusters"; 27 | 28 | public static final String REDISPROXYHOST="redisProxyHost"; 29 | 30 | public static final String REDISPROXYPORT="redisProxyPort"; 31 | 32 | public static final String REDISPROXYCLUSTER="redisProxyCluster"; 33 | 34 | public static final String REDISPROXYMASTER="redisProxyMaster"; 35 | 36 | public static final String REDISPROXYMASTERS="redisProxyMasters"; 37 | 38 | public static final String REDISPROXYNODE="redisProxyNode"; 39 | 40 | public static final String ALGORITHMREF="algorithm-ref"; 41 | 42 | public static final String LOADCLUSTERBALANCE="loadClusterBalance"; 43 | 44 | public static final String LOADMASTERRBALANCE="loadMasterBalance"; 45 | } 46 | -------------------------------------------------------------------------------- /nredis-proxy-spring/src/main/resources/META-INF/redisProxy.xsd: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 15 | 17 | 19 | 21 | 23 | 25 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 41 | 43 | 45 | 47 | 49 | 51 | 52 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 69 | 71 | 73 | 75 | 76 | 77 | 78 | 79 | -------------------------------------------------------------------------------- /nredis-proxy-spring/src/main/resources/META-INF/spring.handlers: -------------------------------------------------------------------------------- 1 | http\://www.nredisproxy.com/redisProxy=com.opensource.netty.redis.proxy.spring.handler.RedisProxyHandlerSupport -------------------------------------------------------------------------------- /nredis-proxy-spring/src/main/resources/META-INF/spring.schemas: -------------------------------------------------------------------------------- 1 | http\://www.nredisproxy.com/redisProxy/redisProxy.xsd=META-INF/redisProxy.xsd --------------------------------------------------------------------------------