public boolean isAvailable() { for (JedisPool jedisPool : jedisPools.values()) { Jedis jedis = jedisPool.getResource(); boolean isBroken = false; try { if (jedis.isConnected()) { return true; // 至少需单台机器可用 } } catch (JedisConnectionException e) { isBroken = true; } finally { if (isBroken) { jedisPool.returnBrokenResource(jedis); } else { jedisPool.returnResource(jedis); } } } return false; }
public void publish(byte[] channel, byte[] message) { Collection<JedisPool> poolCollection = jedisCluster.getClusterNodes().values(); Iterator<JedisPool> iterator = poolCollection.iterator(); if (iterator.hasNext()) { JedisPool jedisPool = (JedisPool)iterator.next(); Jedis jedis = null; try { jedis = jedisPool.getResource(); jedis.publish(channel, message); } catch (Exception var11) { throw new RuntimeException(var11); } finally { jedisPool.returnResourceObject(jedis); } } }
public void connect() { this.instance.log(Level.INFO, "Connecting to database..."); JedisPoolConfig jedisConfiguration = new JedisPoolConfig(); jedisConfiguration.setMaxTotal(-1); jedisConfiguration.setJmxEnabled(false); Logger logger = Logger.getLogger(JedisPool.class.getName()); logger.setLevel(Level.OFF); this.jedisPool = new JedisPool(jedisConfiguration, this.instance.getConfiguration().redisIp, this.instance.getConfiguration().redisPort, 0, this.instance.getConfiguration().redisPassword); try { this.jedisPool.getResource().close(); } catch (Exception e) { this.instance.log(Level.SEVERE, "Can't connect to the database!"); System.exit(8); } this.instance.log(Level.INFO, "Connected to database."); }
@SuppressWarnings("deprecation") @Override public <T> T call(JedisPool jedisPool) { Jedis jedis = null; try { jedis = jedisPool.getResource(); return exec(jedis); } catch (Exception e) { logger.error("jedisPool getResouce or exec has exception"); throw e; } finally { if (jedis != null) { jedisPool.returnResource(jedis); } } }
private JedisPool toJedisPool0() { return new JedisPool(new GenericObjectPoolConfig(), this.getHost(), this.getPort(), this.getTimeout(), this.getPassword(), this.getDatabase()) { @Override public Jedis getResource() { try { return super.getResource(); } catch (JedisConnectionException var2) { RedisConfig.LOGGER.error(RedisConfig.this.toString(), var2); throw new JedisConnectionException(RedisConfig.this.toString(), var2); } } @Override public void close() { } }; }
/** * Create a new client to a RediSearch index * @param indexName the name of the index we are connecting to or creating * @param host the redis host * @param port the redis pot */ public Client(String indexName, String host, int port, int timeout, int poolSize) { JedisPoolConfig conf = new JedisPoolConfig(); conf.setMaxTotal(poolSize); conf.setTestOnBorrow(false); conf.setTestOnReturn(false); conf.setTestOnCreate(false); conf.setTestWhileIdle(false); conf.setMinEvictableIdleTimeMillis(60000); conf.setTimeBetweenEvictionRunsMillis(30000); conf.setNumTestsPerEvictionRun(-1); conf.setFairness(true); pool = new JedisPool(conf, host, port, timeout); this.indexName = indexName; this.commands = new Commands.SingleNodeCommands(); }
@Override public boolean available() { for (JedisPool jedisPool : jedisPools.values()) { Jedis jedis = jedisPool.getResource(); try { if (jedis.isConnected()) { return true; // 至少需单台机器可用 } } catch (JedisConnectionException e) { logger.error("Jedis Connection Exception", e); } finally { if(jedis != null){ jedis.close(); } } } return false; }
public static void main(String[] args) { //定义redis的连接池 JedisPool jedisPool = new JedisPool(new GenericObjectPoolConfig(), "127.0.0.1", 6379, 30000); // JedisPool jedisPool = new JedisPool(new GenericObjectPoolConfig(), // "127.0.0.1", 6379, 30000, "123456"); //有密码 //create, config and start Spider spider = Spider.create() //创建爬虫实例 .setThreadCount(10) //设置任务线程池数量 .addStartRequests("http://blog.csdn.net/") //添加起始url .setPageProcessor(new HelloWorldPageProcessor()) //设置页面解析器 .setScheduler(new RedisScheduler(jedisPool)) //设置请求任务调度器 .setPipeline(new HelloWorldPipeline()); //结果集处理器 //监控 SpiderMonitor.register(spider); //启动 spider.start(); }
@Before public void setUp() throws IOException { initMocks(this); final Random random = new SecureRandom(); redisServer = new RedisServer(); redisServer.start(); pool = new JedisPool(); repository = new RedisKeyRepository(pool); manager = new RedisKeyManager(random, pool, repository); manager.setMaxActiveKeys(3); clearData(); manager.initialiseNewRepository(); resource = new ProtectedResource(repository, random); }
@Override public Optional<List<String>> searchForUsersByExpression(String expression) { System.out.println("expression: " + expression); JedisPool jedisPool = JedisFactory.getPool(); try (Jedis jedis = jedisPool.getResource()) { if (jedis.exists("0")) { jedis.del("0"); } long lenght = jedis.zcard("all_users"); Set<String> sresult = jedis.zrange("all_users", 0, lenght); for (Iterator<String> iterator = sresult.iterator(); iterator.hasNext();) { String iter = iterator.next(); System.out.println("Iterator: " + iter); if (iter.length() >= expression.length() && iter.substring(0, expression.length()).equals(expression)) { jedis.lpush("0", iter); System.out.println("Suche hinzugefuegt: " + iter); } } return Optional.of(jedis.lrange("0", 0, 1)); } catch (Exception e) { System.out.println("Mock SearchUserByExpression: " + expression); e.printStackTrace(); return Optional.of(new ArrayList<String>()); } // return Optional.ofNullable("searchForUsersByExpression: // Redis-Answer-Expression"); }
private List<User> transformResponseToUserList(List<String> userList) { JedisPool jedisPool = JedisFactory.getPool(); try (Jedis jedis = jedisPool.getResource()) { System.out.println("Die Uebergebene userList" + userList.toString()); List<User> users = new ArrayList<>(); for (int i = 0; i < userList.size(); i++) { String keyUser = userList.get(i); System.out.println("keyUser: " + keyUser); // String pw = jedis.hget(keyUser, "pw"); User user = new User(jedis.hget(keyUser, "name"), null); users.add(user); } System.out.println("users:" + users); return users; } catch (Exception e) { System.out.println("transformResponseToUserList"); e.printStackTrace(); return null; } }
@Test public void checkJedisIsReusedWhenReturned() { JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.getHost(), hnp.getPort()); Jedis jedis = pool.getResource(); jedis.auth("foobared"); jedis.set("foo", "0"); pool.returnResource(jedis); jedis = pool.getResource(); jedis.auth("foobared"); jedis.incr("foo"); pool.returnResource(jedis); pool.destroy(); assertTrue(pool.isClosed()); }
/** * 拦截所有调用,选择正确的实例执行命令 * @param o 调用实例 * @param method 调用方法 * @param args 方法参数 * @param methodProxy 方法代理 * @return 命令返回值 * @throws Throwable 方法执行异常或连接异常 */ @Override public Object intercept(Object o, Method method, Object[] args, MethodProxy methodProxy) throws Throwable { GedisInstanceType type; if (READ_METHOD_LIST.contains(method.getName())) { type = GedisInstanceType.READ; } else { type = GedisInstanceType.WRITE; } JedisPool pool = getJedisPoolByType(type); Jedis jedis = pool.getResource(); try { return method.invoke(jedis, args); } catch (Exception e) { jedis.close(); throw e; } finally { jedis.close(); } }
@Test public void selectDatabaseOnActivation() { JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.getHost(), hnp.getPort(), 2000, "foobared"); Jedis jedis0 = pool.getResource(); assertEquals(0L, jedis0.getDB().longValue()); jedis0.select(1); assertEquals(1L, jedis0.getDB().longValue()); pool.returnResource(jedis0); Jedis jedis1 = pool.getResource(); assertTrue("Jedis instance was not reused", jedis1 == jedis0); assertEquals(0L, jedis1.getDB().longValue()); pool.returnResource(jedis1); pool.destroy(); assertTrue(pool.isClosed()); }
@Override public void connect(NURL nurl) { super.connect(nurl); this.retryPeriod = nurl.getParameter("retryPeriod", retryPeriod); JedisPoolConfig config = new JedisPoolConfig(); Map<String, String> parameters = nurl.getParameters(); if (parameters != null) { if (!parameters.isEmpty()) { try { Beans.copyProperties(config, nurl.getParameters()); } catch (Exception e) { logger.error("The copy properties exception.", e); } } } jedisPool = new JedisPool(config, nurl.getHost(), nurl.getPort()); }
@Test public void checkResourceIsCloseable() { GenericObjectPoolConfig config = new GenericObjectPoolConfig(); config.setMaxTotal(1); config.setBlockWhenExhausted(false); JedisPool pool = new JedisPool(config, hnp.getHost(), hnp.getPort(), 2000, "foobared"); Jedis jedis = pool.getResource(); try { jedis.set("hello", "jedis"); } finally { jedis.close(); } Jedis jedis2 = pool.getResource(); try { assertEquals(jedis, jedis2); } finally { jedis2.close(); } }
@Test public void getNumActiveReturnsTheCorrectNumber() { JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.getHost(), hnp.getPort(), 2000); Jedis jedis = pool.getResource(); jedis.auth("foobared"); jedis.set("foo", "bar"); assertEquals("bar", jedis.get("foo")); assertEquals(1, pool.getNumActive()); Jedis jedis2 = pool.getResource(); jedis.auth("foobared"); jedis.set("foo", "bar"); assertEquals(2, pool.getNumActive()); pool.returnResource(jedis); assertEquals(1, pool.getNumActive()); pool.returnResource(jedis2); assertEquals(0, pool.getNumActive()); pool.destroy(); }
public void subscribe(JedisPubSub jedisPubSub, String channel) { Collection<JedisPool> poolCollection = jedisCluster.getClusterNodes().values(); Iterator iterator = poolCollection.iterator(); while(iterator.hasNext()) { JedisPool jedisPool = (JedisPool)iterator.next(); Jedis jedis = null; try { jedis = jedisPool.getResource(); jedis.subscribe(jedisPubSub, new String[]{channel}); } catch (Exception var11) { throw new RuntimeException(var11); } finally { jedisPool.returnResourceObject(jedis); } } }
public void publish(String channel, String message) { Collection<JedisPool> poolCollection = jedisCluster.getClusterNodes().values(); Iterator<JedisPool> iterator = poolCollection.iterator(); if (iterator.hasNext()) { JedisPool jedisPool = (JedisPool)iterator.next(); Jedis jedis = null; try { jedis = jedisPool.getResource(); jedis.publish(channel, message); } catch (Exception var11) { throw new RuntimeException(var11); } finally { jedisPool.returnResourceObject(jedis); } } }
public boolean isAvailable() { for (JedisPool jedisPool : jedisPools.values()) { try { Jedis jedis = jedisPool.getResource(); try { if (jedis.isConnected()) { return true; // 至少需单台机器可用 } } finally { jedisPool.returnResource(jedis); } } catch (Throwable t) { } } return false; }
@Override public boolean exists(final String key) { JedisPool jedisPool = PoolThreadLocal.getPool(); return new AbstractCommandCall() { @Override public <T> T exec(JedisCommands commands) { return (T) commands.exists(key); } }.call(jedisPool); }
@Override public boolean expireat(final String key, final String val, final int cacheTime) { JedisPool jedisPool = PoolThreadLocal.getPool(); return new AbstractCommandCall() { @Override public <T> T exec(JedisCommands commands) { commands.set(key, val); if (cacheTime > 0) { commands.expire(key, cacheTime); } return (T) Boolean.TRUE; } }.call(jedisPool); }
@Override public boolean del(final String key) { JedisPool jedisPool = PoolThreadLocal.getPool(); return new AbstractCommandCall() { @Override public <T> T exec(JedisCommands commands) { commands.del(key); return (T) Boolean.TRUE; } }.call(jedisPool); }
public static <T> T execute(JedisPool jedisPool, JedisCallback<T> callback) { Jedis jedis = null; try { jedis = jedisPool.getResource(); return callback.doInJedis(jedis); } finally { if (jedis != null) { jedis.close(); } } }
public RedisGetAll(JedisPool jedisPool, String key, Map<byte[], byte[]>[] redisDataList, int index) { super(jedisPool, key); this.redisDataList = redisDataList; this.index = index; command = Command.GET_ALL; }
public void afterPropertiesSet() throws Exception { if(StringUtils.isEmpty(password)){ password = null; } if(poolConfig != null){ jedisPool = new JedisPool(poolConfig, host, port, timeout, password, database); } }
public static void main(String[] args) { JedisPool jedisPool1 = JedisTemplate.getJedisPool(); JedisPool jedisPool2 = JedisTemplate.getJedisPool(); System.out.println(jedisPool1.hashCode() == jedisPool2.hashCode()); Jedis jedis1 = JedisTemplate.getJedis(); Jedis jedis2 = JedisTemplate.getJedis(); System.out.println(jedis1.hashCode() == jedis2.hashCode()); }
public static Jedis connect() { try { if(instance == null) { URI redisUri = new URI(System.getenv("REDISCLOUD_URL")); instance = new JedisPool(new JedisPoolConfig(), redisUri.getHost(), redisUri.getPort(), Protocol.DEFAULT_TIMEOUT, redisUri.getUserInfo().split(":", 2)[1]).getResource(); } return instance; } catch (Exception e) { Logger.getLogger(RedisConnection.class.getName()).warning(e.getMessage()); } return null; }
public RedisGetChunk(JedisPool jedisPool, String key, String field, byte[][] redisDataList, int index) { super(jedisPool, key); this.field = field; this.redisDataList = redisDataList; this.index = index; command = Command.GET_CHUNK; }
/** * @param pool connection to Redis */ @Inject public RedisKeyRepository(final JedisPool pool) { if (pool == null) { throw new IllegalArgumentException("pool cannot be null"); } this.pool = pool; }
@Override public Map<String, JedisPool> getClusterNodes() { Span span = helper.buildSpan("getClusterNodes"); try { return super.getClusterNodes(); } catch (Exception e) { onError(e, span); throw e; } finally { span.finish(); } }
@Bean(name="o2iConfigJedisPool") public JedisPool getJedisPool(@Qualifier("o2iConfigJedisPoolConfig") JedisPoolConfig config, @Value("${spring.redis.o2iConfig.host}")String host, @Value("${spring.redis.o2iConfig.port}")int port, @Value("${spring.redis.o2iConfig.timeOut}")int timeOut) { return new JedisPool(config, host, port, timeOut); }
@Override public Optional<String> id() { JedisPool jedisPool = JedisFactory.getPool(); try (Jedis jedis = jedisPool.getResource()) { return Optional.of(jedis.set("id", "1")); } catch (Exception e) { System.out.println("Mock id CatchBlock"); e.printStackTrace(); return null; } }
@Provides @Named("authenticatableRedisDao") @Singleton public RedisDao<AuthenticationCredentials, AuthenticatedEntity> getAuthenticatableRedisDao(JedisPool jedisPool) { return new RedisDaoImpl<AuthenticationCredentials, AuthenticatedEntity>() .setPrefix("AUTHENTICABLE") .setPool(jedisPool) .setTtlSeconds(172800) .setDeserializer((json) -> AuthenticatableRedisSerializer.deserialize((String) json)) .setSerializer((authenticatable) -> AuthenticatableRedisSerializer.serialize((AuthenticatedEntity) authenticatable)); }
@Override public Optional<Tweet> getTweets(User user, String id) { JedisPool jedisPool = JedisFactory.getPool(); try (Jedis jedis = jedisPool.getResource()) { String key = user.getName() + ":tweet:" + id; Tweet tweet = new Tweet(null, null, user, id); tweet.setMessage(jedis.hget(key, "message")); tweet.setDate(jedis.hget(key, "date")); return Optional.of(tweet); } catch (Exception e) { System.out.println("Mock getTweets"); e.printStackTrace(); return null; } }
@Primary @Bean(name="monitorJedisPool") public JedisPool getJedisPool(@Qualifier("monitorJedisPoolConfig") JedisPoolConfig config, @Value("${spring.redis.monitor.host}")String host, @Value("${spring.redis.monitor.port}")int port, @Value("${spring.redis.monitor.timeOut}")int timeOut) { return new JedisPool(config, host, port, timeOut); }
@Override public Optional<List<String>> getPersonalTweets(User user) { JedisPool jedisPool = JedisFactory.getPool(); try (Jedis jedis = jedisPool.getResource()) { String key = user.getName() + ":personal"; return Optional.of(jedis.lrange(key, 0, -1)); } catch (Exception e) { System.out.println("Mock getPersonalTweets"); e.printStackTrace(); return null; } // return Optional.ofNullable("getPersonalTweets: Redis-Answer-Expression"); }
public static void connect(Connection connection) { JedisPool jedisPool = createJedisPool(connection); try (Jedis jedis = jedisPool.getResource()) { jedis.get("name"); } // Assign values after successfully connected. JedisManager.jedisPool = jedisPool; JedisManager.connection = connection; }
@Override public Optional<User> getUserByUsername(String username) { JedisPool jedisPool = JedisFactory.getPool(); try (Jedis jedis = jedisPool.getResource()) { String key = username; User user = new User(jedis.hget(key, "name"), null); return Optional.of(user); } catch (Exception e) { System.out.println("Mock getUserByUsername"); e.printStackTrace(); return null; } // return Optional.ofNullable("getUserByUsername: " + username); }