|
| 1 | +package io.kimmking.cache; |
| 2 | + |
| 3 | +import redis.clients.jedis.HostAndPort; |
| 4 | +import redis.clients.jedis.Jedis; |
| 5 | +import redis.clients.jedis.JedisPoolConfig; |
| 6 | +import redis.clients.jedis.JedisSentinelPool; |
| 7 | + |
| 8 | +import java.util.HashSet; |
| 9 | +import java.util.Set; |
| 10 | + |
| 11 | +public final class SentinelJedis { |
| 12 | + |
| 13 | + //可用连接实例的最大数目,默认为8; |
| 14 | + //如果赋值为-1,则表示不限制,如果pool已经分配了maxActive个jedis实例,则此时pool的状态为exhausted(耗尽) |
| 15 | + private static Integer MAX_TOTAL = 16; |
| 16 | + //控制一个pool最多有多少个状态为idle(空闲)的jedis实例,默认值是8 |
| 17 | + private static Integer MAX_IDLE = 12; |
| 18 | + //等待可用连接的最大时间,单位是毫秒,默认值为-1,表示永不超时。 |
| 19 | + //如果超过等待时间,则直接抛出JedisConnectionException |
| 20 | + private static Integer MAX_WAIT_MILLIS = 10000; |
| 21 | + //客户端超时时间配置 |
| 22 | + private static Integer TIMEOUT = 10000; |
| 23 | + //在borrow(用)一个jedis实例时,是否提前进行validate(验证)操作; |
| 24 | + //如果为true,则得到的jedis实例均是可用的 |
| 25 | + private static Boolean TEST_ON_BORROW = true; |
| 26 | + //在空闲时检查有效性, 默认false |
| 27 | + private static Boolean TEST_WHILE_IDLE = true; |
| 28 | + //是否进行有效性检查 |
| 29 | + private static Boolean TEST_ON_RETURN = true; |
| 30 | + |
| 31 | + private static JedisSentinelPool POOL = createJedisPool(); |
| 32 | + |
| 33 | + /** |
| 34 | + * 创建连接池 |
| 35 | + */ |
| 36 | + private static JedisSentinelPool createJedisPool() { |
| 37 | + JedisPoolConfig config = new JedisPoolConfig(); |
| 38 | + /*注意: |
| 39 | + 在高版本的jedis jar包,比如本版本2.9.0,JedisPoolConfig没有setMaxActive和setMaxWait属性了 |
| 40 | + 这是因为高版本中官方废弃了此方法,用以下两个属性替换。 |
| 41 | + maxActive ==> maxTotal |
| 42 | + maxWait==> maxWaitMillis |
| 43 | + */ |
| 44 | + config.setMaxTotal(MAX_TOTAL); |
| 45 | + config.setMaxIdle(MAX_IDLE); |
| 46 | + config.setMaxWaitMillis(MAX_WAIT_MILLIS); |
| 47 | + config.setTestOnBorrow(TEST_ON_BORROW); |
| 48 | + config.setTestWhileIdle(TEST_WHILE_IDLE); |
| 49 | + config.setTestOnReturn(TEST_ON_RETURN); |
| 50 | + String masterName = "mymaster"; |
| 51 | + Set<String> sentinels = new HashSet<String>(); |
| 52 | + sentinels.add(new HostAndPort("127.0.0.1",26379).toString()); |
| 53 | + sentinels.add(new HostAndPort("127.0.0.1",26380).toString()); |
| 54 | + JedisSentinelPool pool = new JedisSentinelPool(masterName, sentinels, config, TIMEOUT, null); |
| 55 | + return pool; |
| 56 | + } |
| 57 | + |
| 58 | + public static Jedis getJedis() { |
| 59 | + return POOL.getResource(); |
| 60 | + } |
| 61 | + |
| 62 | + public static void close(){ |
| 63 | + POOL.close(); |
| 64 | + } |
| 65 | + |
| 66 | +} |
0 commit comments