Java Code Examples for redis.clients.jedis.JedisPoolConfig

The following are top voted examples for showing how to use redis.clients.jedis.JedisPoolConfig. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: groot   File: RedisConfiguration.java   View source code 8 votes vote down vote up
private void jedisConnConfig(final JedisConnectionFactory jedisConnectionFactory) {
    JedisPoolConfig poolConfig = new JedisPoolConfig();
    try {
        poolConfig.setMaxTotal(Integer.parseInt(REDIS_MAXTOTAL.getValue()));
        poolConfig.setMaxIdle(Integer.parseInt(REDIS_MAXIDLE.getValue()));
        poolConfig.setBlockWhenExhausted(true);
        if (!"".equals(REDIS_PASSWORD.getValue())) {
            jedisConnectionFactory.setPassword(REDIS_PASSWORD.getValue());
        }
        if (!"".equals(REDIS_DATABASE.getValue())) {
            jedisConnectionFactory.setDatabase(Integer.parseInt(REDIS_DATABASE.getValue()));
        }
        jedisConnectionFactory.setPoolConfig(poolConfig);
        jedisConnectionFactory.setUsePool(true);
        jedisConnectionFactory.setTimeout(Integer.parseInt(REDIS_TIMEOUT.getValue()));
    } catch (Exception e) {
        LOGGER.error(e.getMessage(), e);
    }
}
 
Example 2
Project: Building_Effective_Microservices   File: GuiceBindings.java   View source code 7 votes vote down vote up
@Override
protected void configure() {
	bind(HealthCheckHandler.class).toInstance(new HealthcheckResource());
	
	bind(RequrestAdapter.class).to(RxNettyServiceAdapter.class);
	
	bind(MeetupResource.class).asEagerSingleton();
	bind(MeetupService.class).to(MeetupServiceImpl.class);
	bind(MeetupDAO.class).to(MeetupDAOImpl.class);

	bind(JedisPool.class).toInstance(
			new JedisPool(
					new JedisPoolConfig(), 
					 ConfigurationManager.getConfigInstance().getString("redis_ip","localhost")));
	
}
 
Example 3
Project: nighthawk   File: TestJedisProxyPool.java   View source code 7 votes vote down vote up
@Test
public void test_jedis_tracer() throws Exception {
    Brave.Builder builder = new Brave.Builder("jedis-interceptor-test");
    builder.spanCollector(HttpSpanCollector.create("http://192.168.150.132:9411", new EmptySpanCollectorMetricsHandler()));
    builder.traceSampler(Sampler.ALWAYS_SAMPLE);
    Brave brave = builder.build();
    JaRedisInterceptor.setClientTracer(brave.clientTracer());

    JedisPoolConfig config = new JedisPoolConfig();
    JaRedisPool proxyPool = new JaRedisPool(config, "127.0.0.1", 6379);
    Jedis jedis = proxyPool.getResource();
    jedis.set("hello", "world");
    Assert.assertEquals(jedis.get("hello"), "world");
    jedis.hgetAll("hello-map");
    jedis.close();
    // sleep 3s in case spanCollector not flushed
    Thread.sleep(3000);
}
 
Example 4
Project: JRediClients   File: JedisPoolTest.java   View source code 7 votes vote down vote up
@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());
}
 
Example 5
Project: JRediSearch   File: Client.java   View source code 7 votes vote down vote up
/**
 * 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();
}
 
Example 6
Project: coon   File: RedisMconf.java   View source code 6 votes vote down vote up
@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());
}
 
Example 7
Project: SamaGamesCore   File: DatabaseConnector.java   View source code 6 votes vote down vote up
private void connect()
{
    JedisPoolConfig config = new JedisPoolConfig();
    config.setMaxTotal(-1);
    config.setJmxEnabled(false);

    try
    {
        this.cachePool = new JedisPool(config, this.bungee.getIp(), this.bungee.getPort(), 0, this.bungee.getPassword());
        this.cachePool.getResource().close();

        this.plugin.log(Level.INFO, "Connected to database.");
    }
    catch (Exception e)
    {
        plugin.getLogger().log(Level.SEVERE, "Can't connect to the database!", e);
        Bukkit.shutdown();
    }
}
 
Example 8
Project: log4j2-redis-appender   File: RedisConnectionPoolConfig.java   View source code 6 votes vote down vote up
private static JedisPoolConfig createJedisPoolConfig(Builder builder) {
    JedisPoolConfig config = new JedisPoolConfig();
    config.setMaxTotal(builder.maxTotal);
    config.setMaxIdle(builder.maxIdle);
    config.setMinIdle(builder.minIdle);
    config.setLifo(builder.lifo);
    config.setFairness(builder.fairness);
    config.setMaxWaitMillis(builder.maxWaitMillis);
    config.setMinEvictableIdleTimeMillis(builder.minEvictableIdleTimeMillis);
    config.setSoftMinEvictableIdleTimeMillis(builder.softMinEvictableIdleTimeMillis);
    config.setNumTestsPerEvictionRun(builder.numTestsPerEvictionRun);
    config.setTestOnCreate(builder.testOnCreate);
    config.setTestOnBorrow(builder.testOnBorrow);
    config.setTestOnReturn(builder.testOnReturn);
    config.setTestWhileIdle(builder.testWhileIdle);
    config.setTimeBetweenEvictionRunsMillis(builder.timeBetweenEvictionRunsMillis);
    config.setEvictionPolicyClassName(builder.evictionPolicyClassName);
    config.setBlockWhenExhausted(builder.blockWhenExhausted);
    config.setJmxEnabled(builder.jmxEnabled);
    config.setJmxNameBase(builder.jmxNameBase);
    config.setJmxNamePrefix(builder.jmxNamePrefix);
    return config;
}
 
Example 9
Project: seldon-core   File: RedisConfig.java   View source code 6 votes vote down vote up
@Bean
public RedisConnectionFactory redisConnectionFactory() {
    String default_host = "localhost";
    int port = 6379;
    String host = null;
    { // setup the host using the env vars
        host = System.getenv().get(SELDON_CLUSTER_MANAGER_REDIS_HOST_KEY);
        if (host == null) {
            logger.error(String.format("FAILED to find env var [%s]", SELDON_CLUSTER_MANAGER_REDIS_HOST_KEY));
            host = default_host;
        }
    }

    logger.info(String.format("setting up connection factory, host[%s] port[%d]", host, port));
    JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory();
    jedisConnectionFactory.setHostName(host);
    jedisConnectionFactory.setPort(port);
    jedisConnectionFactory.setPassword("");
    jedisConnectionFactory.setUsePool(true);
    jedisConnectionFactory.setPoolConfig(new JedisPoolConfig());
    return jedisConnectionFactory;
}
 
Example 10
Project: JRediClients   File: JedisPoolTest.java   View source code 6 votes vote down vote up
@Test
public void nonDefaultDatabase() {
  JedisPool pool0 = new JedisPool(new JedisPoolConfig(), hnp.getHost(), hnp.getPort(), 2000,
      "foobared");
  Jedis jedis0 = pool0.getResource();
  jedis0.set("foo", "bar");
  assertEquals("bar", jedis0.get("foo"));
  pool0.returnResource(jedis0);
  pool0.destroy();
  assertTrue(pool0.isClosed());

  JedisPool pool1 = new JedisPool(new JedisPoolConfig(), hnp.getHost(), hnp.getPort(), 2000,
      "foobared", 1);
  Jedis jedis1 = pool1.getResource();
  assertNull(jedis1.get("foo"));
  pool1.returnResource(jedis1);
  pool1.destroy();
  assertTrue(pool1.isClosed());
}
 
Example 11
Project: JRediClients   File: JedisPoolTest.java   View source code 6 votes vote down vote up
@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());
}
 
Example 12
Project: JRediClients   File: JedisPoolTest.java   View source code 6 votes vote down vote up
@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();
}
 
Example 13
Project: JRediClients   File: JedisPoolTest.java   View source code 6 votes vote down vote up
@Test
public void testAddObject() {
  JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.getHost(), hnp.getPort(), 2000);
  pool.addObjects(1);
  assertEquals(pool.getNumIdle(), 1);
  pool.destroy();

}
 
Example 14
Project: JRediClients   File: JedisPoolTest.java   View source code 6 votes vote down vote up
@Test
public void testCloseConnectionOnMakeObject() {
  JedisPoolConfig config = new JedisPoolConfig();
  config.setTestOnBorrow(true);
  JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.getHost(), hnp.getPort(), 2000,
      "wrong pass");
  Jedis jedis = new Jedis("redis://:[email protected]:6379/");
  int currentClientCount = getClientCount(jedis.clientList());
  try {
    pool.getResource();
    fail("Should throw exception as password is incorrect.");
  } catch (Exception e) {
    assertEquals(currentClientCount, getClientCount(jedis.clientList()));
  }

}
 
Example 15
Project: daf-cacher   File: ApiService.java   View source code 6 votes vote down vote up
public ApiService(final Properties properties) throws URISyntaxException {
    this.properties = properties;
    this.requestLog = new RequestLogFactory(LOGGER).create();
    EmbeddedJettyFactory factory = new EmbeddedJettyFactoryConstructor(requestLog).create();
    EmbeddedServers.add(EmbeddedServers.Identifiers.JETTY, factory);
    final JedisPoolConfig poolConfig = new JedisPoolConfig();
    poolConfig.setMaxTotal(128); // maximum active connections
    poolConfig.setMaxIdle(32);  // maximum idle connections

    this.jedisPool = new JedisPool(poolConfig, new URI(properties.getProperty("caching.redis_host")));
    this.supersetCredential = new Credential(
            properties.getProperty("superset.user"),
            properties.getProperty("superset.password")
    );

    this.dafApiCredential = new Credential(
            properties.getProperty("daf_api.user"),
            properties.getProperty("daf_api.password")
    );

}
 
Example 16
Project: x7   File: JedisConnector_Persistence.java   View source code 6 votes vote down vote up
public static JedisConnector_Persistence getInstance() {
	if (instance == null) {
		instance = new JedisConnector_Persistence();
		JedisPoolConfig config = new JedisPoolConfig();
		config.setMaxTotal(Configs.getIntValue("x7.redis.max"));
		config.setMaxIdle(Configs.getIntValue("x7.redis.idle"));
		config.setJmxEnabled(true);
		config.setJmxNamePrefix("redis-persistence");
		config.setTestOnBorrow(true);

		System.out.println("x7.redis.ip.persistence = " + Configs.getString("x7.redis.ip.persistence"));
		System.out.println("x7.redis.port.persistence = " + Configs.getString("x7.redis.port.persistence"));

		pool = new JedisPool(config, Configs.getString("x7.redis.ip.persistence"),
				Configs.getIntValue("x7.redis.port.persistence")); // 6379
	}
	return instance;
}
 
Example 17
Project: JInsight   File: JedisPoolInstrumentationTest.java   View source code 6 votes vote down vote up
@Before
public void setUp() throws Exception {
  MetricRegistry registry = RegistryService.getMetricRegistry();

  String redisAddr = System.getProperty("redis.addr");
  uri = new URI("redis://" + redisAddr);

  final JedisPoolConfig poolConfig = new JedisPoolConfig();
  poolConfig.setMaxTotal(5);
  pool = new JedisPool(poolConfig, uri);

  getTracker = new CountTracker(registry, JedisRuleHelper.POOL_GET_METRIC);
  getTracker.registerTimer();
  releaseTracker = new CountTracker(registry, JedisRuleHelper.POOL_RELEASE_METRIC);
  releaseTracker.registerTimer();
}
 
Example 18
Project: wx-idk   File: JedisPoolConfigFactory.java   View source code 6 votes vote down vote up
private JedisPoolConfigFactory() {
	config = new JedisPoolConfig();
	//连接耗尽时是否阻塞, false报异常,ture阻塞直到超时, 默认true
   	config.setBlockWhenExhausted(true);
   	//设置的逐出策略类名, 默认DefaultEvictionPolicy(当连接超过最大空闲时间,或连接数超过最大空闲连接数)
   	config.setEvictionPolicyClassName("org.apache.commons.pool2.impl.DefaultEvictionPolicy");
   	//是否启用pool的jmx管理功能, 默认true
   	config.setJmxEnabled(true);
   	//是否启用后进先出, 默认true
   	config.setLifo(true);
   	//最大空闲连接数, 默认8个
   	config.setMaxIdle(Integer.parseInt(Config.getAttribute("maxIdle")));
   	//最大连接数, 默认8个
   	config.setMaxTotal(Integer.parseInt(Config.getAttribute("maxTotal")));
   	//获取连接时的最大等待毫秒数(如果设置为阻塞时BlockWhenExhausted),如果超时就抛异常, 小于零:阻塞不确定的时间,  默认-1
   	config.setMaxWaitMillis(Integer.parseInt(Config.getAttribute("maxWait")));
   	//最小空闲连接数, 默认0
   	config.setMinIdle(Integer.parseInt(Config.getAttribute("minIdle")));
   	//在获取连接的时候检查有效性, 默认false
   	config.setTestOnBorrow(Boolean.parseBoolean(Config.getAttribute("testOnBorrow")));
   	//在空闲时检查有效性, 默认false
   	config.setTestWhileIdle(Boolean.parseBoolean(Config.getAttribute("testOnReturn")));
}
 
Example 19
Project: Elune   File: RedisManager.java   View source code 6 votes vote down vote up
private void createJedisPool() {

        JedisPoolConfig config = new JedisPoolConfig();

        // 设置最大连接数
        config.setMaxTotal(500);

        // 设置最大阻塞时间(毫秒)
        config.setMaxWaitMillis(1000);

        // 设置空闲连接数
        config.setMaxIdle(20);
        config.setMinIdle(10);

        // 创建连接池
        pool = new JedisPool(config, appConfig.get(CONFIG_KEY_REDIS_HOST, DEFAULT_REDIS_HOST), appConfig.getInt(CONFIG_KEY_REDIS_PORT, DEFAULT_REDIS_PORT), Protocol.DEFAULT_TIMEOUT, appConfig.get(CONFIG_KEY_REDIS_PASS, ""));
    }
 
Example 20
Project: asura   File: RedisServiceFactory.java   View source code 6 votes vote down vote up
@Override
public void afterPropertiesSet() throws Exception {
	final JedisPoolConfig config = JedisPoolConfigFactory.createJedisPoolConfig();

	final Set<JedisShardInfo> shardInfos = new HashSet<JedisShardInfo>();
	final HostInfo[] hostInfos = HostInfoFactory.split(hosts);
	for (final HostInfo hostInfo : hostInfos) {
		shardInfos.add(hostInfo.createJedisShardInfo());
	}
	if (redisService == null) {
		final ShardedJedisPool jedisPool = new ShardedJedisPool(config, new ArrayList<JedisShardInfo>(shardInfos));
		redisService = new RedisServiceImpl(jedisPool);
	}

	final RedisServiceProxy redisServiceProxy = new RedisServiceProxy();
	this.redisService = redisServiceProxy.bind(redisService);
}
 
Example 21
Project: asura   File: AbstractRedisCacheClient.java   View source code 6 votes vote down vote up
/**
 * 获取poolconfig
 *
 * @return
 */
public JedisPoolConfig getPoolConfig() {
    JedisPoolConfig config = new JedisPoolConfig();
    if (getMaxIdle() != 0) {
        config.setMaxIdle(getMaxIdle());
    }
    if (getMinIdle() != 0) {
        config.setMinIdle(getMinIdle());
    }
    if (getMaxWaitMillis() != 0) {
        config.setMaxWaitMillis(getMaxWaitMillis());
    }
    if (getMaxTotal() != 0) {
        config.setMaxTotal(getMaxTotal());
    }
    config.setTestOnBorrow(true);
    config.setTestWhileIdle(true);
    return config;
}
 
Example 22
Project: lib-edge   File: RedisSessionConfiguration.java   View source code 6 votes vote down vote up
@Bean
public JedisConnectionFactory connectionFactory() {
  JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
  jedisPoolConfig.setMaxTotal(Integer.parseInt(env.getProperty(REDIS_POOL_MAX_ACTIVE)));
  jedisPoolConfig.setMaxIdle(Integer.parseInt(env.getProperty(REDIS_POOL_MAX_IDLE)));
  jedisPoolConfig.setMinIdle(Integer.parseInt(env.getProperty(REDIS_POOL_MIN_IDLE)));
  jedisPoolConfig.setMaxWaitMillis(Long.parseLong(env.getProperty(REDIS_POOL_MAX_WAIT)));
  jedisPoolConfig.setTestOnBorrow(true);
  jedisPoolConfig.setTestOnReturn(true);
  jedisPoolConfig.setTestWhileIdle(true);

  JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(jedisPoolConfig);
  jedisConnectionFactory.setUsePool(true);
  jedisConnectionFactory.setHostName(env.getProperty((REDIS_REMOTE_HOST)));
  return jedisConnectionFactory;
}
 
Example 23
Project: ECFileCache   File: DecoratedJedisPool.java   View source code 6 votes vote down vote up
/**
 * Constructs a redis pool
 *
 * @param redisAddress redis address, like host:port
 * @return DecoratedJedisPool
 * @throws ECFileCacheException
 */
public static DecoratedJedisPool create(String redisAddress)
    throws ECFileCacheException {
  String[] address = redisAddress.split(ADDRESS_SEP);
  if (address.length < 2) {
    String verbose = String.format("invalid redis address[%s]", redisAddress);
    LOGGER.error(verbose);
    throw new ECFileCacheException(verbose);
  }
  String host = address[0];
  int port = Integer.parseInt(address[1]);

  Validate.isTrue(StringUtils.isNotEmpty(host));
  Validate.isTrue(port > 0);

  JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
  jedisPoolConfig.setMaxTotal(Config.getInstance().getJedisPoolMax());

  return new DecoratedJedisPool(jedisPoolConfig, host, port);
}
 
Example 24
Project: mafia   File: RedisConfig.java   View source code 5 votes vote down vote up
private RedisConnectionFactory getRedisConnectionFactory(int database, String host, String password, int port, int maxIdle, int minIdle, int maxWait) {
    JedisConnectionFactory connectionFactory = new JedisConnectionFactory();
    connectionFactory.setDatabase(database);
    connectionFactory.setHostName(host);
    connectionFactory.setPassword(password);
    connectionFactory.setPort(port);
    JedisPoolConfig poolConfig = new JedisPoolConfig();
    poolConfig.setMaxIdle(maxIdle);
    poolConfig.setMinIdle(minIdle);
    poolConfig.setMaxWaitMillis(maxWait);
    poolConfig.setTestOnBorrow(true);
    poolConfig.setTestOnCreate(true);
    poolConfig.setTestWhileIdle(true);
    connectionFactory.setUsePool(true);
    return connectionFactory;
}
 
Example 25
Project: happylifeplat-transaction   File: JedisClusterConfig.java   View source code 5 votes vote down vote up
@Bean
public JedisPoolConfig getJedisPoolConfig(){
    JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
    jedisPoolConfig.setMaxTotal(redisProperties.getMaxTotal());
    jedisPoolConfig.setMaxIdle(redisProperties.getMaxIdle());
    jedisPoolConfig.setMinIdle(redisProperties.getMinIdle());
    jedisPoolConfig.setMaxWaitMillis(redisProperties.getMaxWaitMillis());
    return jedisPoolConfig;
}
 
Example 26
Project: JavaStudy   File: RedisBeans.java   View source code 5 votes vote down vote up
/**
     *redis 单例
     * @param poolConfig
     * @return
     */
    @Bean(name = "connectionFactory")
    public RedisConnectionFactory connectionFactory(
            JedisPoolConfig poolConfig){
        JedisConnectionFactory jcf=new JedisConnectionFactory();
        jcf.setHostName(this.host);
        jcf.setPort(this.port);
        jcf.setTimeout(timeout);
//        jcf.setPassword(this.password);
        jcf.setPoolConfig(poolConfig);
        return jcf;
    }
 
Example 27
Project: JavaStudy   File: RedisBeans.java   View source code 5 votes vote down vote up
/**
 *redis 集群
 * @return
 */
@Bean(name="clusterConnectionFactory")
public RedisConnectionFactory clusterConnectionFactory(
        JedisPoolConfig poolConfig,
        RedisClusterConfiguration clusterConfig){
    if(clusterConfig!=null){
        return new JedisConnectionFactory(clusterConfig,poolConfig);
    }
    return connectionFactory(poolConfig);
}
 
Example 28
Project: JavaStudy   File: RedisBeans.java   View source code 5 votes vote down vote up
/**
     *redis 主从
     * @return
     */
    @Bean(name="sentinelConnectionFactory")
    public RedisConnectionFactory sentinelConnectionFactory(
            JedisPoolConfig poolConfig,
            RedisSentinelConfiguration sentinelConfig){
        if(sentinelConfig!=null){
            JedisConnectionFactory jcf=new JedisConnectionFactory(sentinelConfig,poolConfig);
            jcf.setHostName(this.host);
            jcf.setPort(this.port);
            jcf.setTimeout(timeout);
//            jcf.setPassword(this.password);
            return jcf;
        }
        return connectionFactory(poolConfig);
    }
 
Example 29
Project: keti   File: LocalRedisConnectionFactoryConfig.java   View source code 5 votes vote down vote up
private RedisConnectionFactory createJedisConnectionFactory(final LocalRedisProperties redisProperties) {
    JedisPoolConfig poolConfig = new JedisPoolConfig();
    poolConfig.setMaxTotal(redisProperties.getMinActive());
    poolConfig.setMinIdle(redisProperties.getMaxActive());
    poolConfig.setMaxWaitMillis(redisProperties.getMaxWaitTime());
    poolConfig.setTestOnBorrow(false);

    JedisConnectionFactory connFactory = new JedisConnectionFactory(poolConfig);
    connFactory.setUsePool(false);
    connFactory.setTimeout(redisProperties.getSoTimeout());
    connFactory.setHostName(redisProperties.getRedisHost());
    connFactory.setPort(redisProperties.getRedisPort());
    return connFactory;
}
 
Example 30
Project: grain   File: RedisManager.java   View source code 5 votes vote down vote up
/**
 * 初始化redis
 * 
 * @param ip
 *            ip地址
 * @param port
 *            端口
 * @param log
 *            日志可以为null
 */
public static void init(String ip, int port, ILog log) {
	RedisManager.log = log;
	JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
	jedisPoolConfig.setMaxTotal(2000);
	jedisPoolConfig.setMaxIdle(200);
	jedisPoolConfig.setMinIdle(0);
	jedisPoolConfig.setTestOnBorrow(true);
	jedisPool = new JedisPool(jedisPoolConfig, ip, port);
	serializer = new SerializingConverter(log);
	deserializer = new DeserializingConverter(log);
}
 
Example 31
Project: JavaStudy   File: RedisClusterApp.java   View source code 5 votes vote down vote up
public static void main(String[] args) {
    //加载服务列表
    Set<HostAndPort> redisClusterNodes =new HashSet<>();
    redisClusterNodes.add(new HostAndPort("192.168.137.147",7001));
    redisClusterNodes.add(new HostAndPort("192.168.137.147",7002));
    redisClusterNodes.add(new HostAndPort("192.168.137.147",7003));
    redisClusterNodes.add(new HostAndPort("192.168.137.147",7004));
    redisClusterNodes.add(new HostAndPort("192.168.137.147",7005));
    redisClusterNodes.add(new HostAndPort("192.168.137.147",7006));

    //redis配置
    JedisPoolConfig jedisPoolConfig=new JedisPoolConfig();
    jedisPoolConfig.setMaxTotal(100);
    jedisPoolConfig.setMaxIdle(20);
    jedisPoolConfig.setMaxWaitMillis(-1);
    jedisPoolConfig.setTestOnBorrow(true);

    //redis集群
    JedisCluster jedisCluster=new JedisCluster(redisClusterNodes,6000,1000,jedisPoolConfig);

    PrinterUtils.printELog(jedisCluster.set("username","tom"));
    PrinterUtils.printELog(jedisCluster.set("age","23"));
    PrinterUtils.printILog(jedisCluster.get("username"));
    PrinterUtils.printILog(jedisCluster.get("age"));
    PrinterUtils.printILog(jedisCluster.get("age"));
    PrinterUtils.printILog(jedisCluster.get("username"));
    PrinterUtils.printILog(jedisCluster.get("password"));
    PrinterUtils.printILog(jedisCluster.getClusterNodes());

    try {
        jedisCluster.close();
    } catch (IOException e) {
        e.printStackTrace();
    }


}
 
Example 32
Project: WiFiProbeAnalysis   File: JedisPoolManager.java   View source code 5 votes vote down vote up
public static void setSharedJedisPool() {
        JedisPoolConfig config = new JedisPoolConfig();//Jedis池配置
        // 共享jedis池,用于集群
        List<JedisShardInfo> jedisShardInfos = new ArrayList<>();
        JedisShardInfo node01 = new JedisShardInfo("120.24.238.195", 6379);
//        JedisShardInfo node02 = new JedisShardInfo("120.25.162.32", 6379);
//        JedisShardInfo node03 = new JedisShardInfo("112.74.114.226", 6379);
        node01.setPassword("110110");
        jedisShardInfos.add(node01);
//        jedisShardInfos.add(node02);
//        jedisShardInfos.add(node03);
        pool = new ShardedJedisPool(config, jedisShardInfos);
        isSetup = true;
    }
 
Example 33
Project: CityPower-Build-Sample   File: CacheConfig.java   View source code 5 votes vote down vote up
@Bean
public JedisConnectionFactory redisConnectionFactory() {
    JedisPoolConfig poolConfig = new JedisPoolConfig();
    poolConfig.setMaxTotal(5);
    poolConfig.setTestOnBorrow(true);
    poolConfig.setTestOnReturn(true);
    JedisConnectionFactory ob = new JedisConnectionFactory(poolConfig);
    ob.setUsePool(true);
    String redishost = cacheProperties.getRedisHost(); //System.getenv("REDISCACHE_HOSTNAME");
    LOG.info("REDISCACHE_HOSTNAME={}", redishost);
    ob.setHostName(redishost);
    String redisport = cacheProperties.getRedisPort().toString(); //System.getenv("REDISCACHE_PORT");
    LOG.info("REDISCACHE_PORT= {}", redisport);
    try {
        ob.setPort(Integer.parseInt(  redisport));
    } catch (NumberFormatException e1) {
        // if the port is not in the ENV, use the default
        ob.setPort(6379);
    }
    String rediskey = cacheProperties.getPrimaryKey(); //System.getenv("REDISCACHE_PRIMARY_KEY");
    LOG.info("REDISCACHE_PRIMARY_KEY= {}", rediskey);
    ob.setPassword(rediskey);
    ob.afterPropertiesSet();
    RedisTemplate<Object,Object> tmp = new RedisTemplate<>();
    tmp.setConnectionFactory(ob);

    //make sure redis connection is working
    try {
        String msg = tmp.getConnectionFactory().getConnection().ping();
        LOG.info("redis ping response="+msg);
        //clear the cache before use
        tmp.getConnectionFactory().getConnection().flushAll();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return ob;
}
 
Example 34
Project: cas-5.1.0   File: RedisTicketRegistryConfiguration.java   View source code 5 votes vote down vote up
private JedisPoolConfig jedisPoolConfig() {
    final RedisTicketRegistryProperties redis = casProperties.getTicket().getRegistry().getRedis();

    final JedisPoolConfig config = new JedisPoolConfig();
    final RedisTicketRegistryProperties.Pool props = redis.getPool();
    config.setMaxTotal(props.getMaxActive());
    config.setMaxIdle(props.getMaxIdle());
    config.setMinIdle(props.getMinIdle());
    config.setMaxWaitMillis(props.getMaxWait());
    return config;
}
 
Example 35
Project: redis_util   File: RedisConnectionUtil.java   View source code 5 votes vote down vote up
public static RedisConnection create() {
    JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
    jedisPoolConfig.setMaxTotal(50);
    jedisPoolConfig.setMaxIdle(10);
    jedisPoolConfig.setMinIdle(1);
    RedisConnection redisConnection = new RedisConnection();
    redisConnection.setIp("10.110.2.56");
    redisConnection.setPort(52981);
    redisConnection.setPwd("hhSbcpotThgWdnxJNhrzwstSP20DvYOldkjf");
    redisConnection.setClientName(Thread.currentThread().getName());
    redisConnection.setTimeOut(600);
    redisConnection.setJedisPoolConfig(jedisPoolConfig);
    return redisConnection;
}
 
Example 36
Project: x7   File: JedisConnector_Cache3.java   View source code 5 votes vote down vote up
public static JedisConnector_Cache3 getInstance(){
	if (instance == null){
		instance = new JedisConnector_Cache3();
		JedisPoolConfig config = new JedisPoolConfig();
		config.setMaxTotal(Configs.getIntValue("x7.redis.max"));
		config.setMaxIdle(Configs.getIntValue("x7.redis.idle"));
		config.setJmxEnabled(true);
		config.setJmxNamePrefix("redis-cahce3");
		config.setTestOnBorrow(true);
		
		pool = new JedisPool( config, Configs.getString("x7.redis.ip.cache3"), Configs.getIntValue("x7.redis.port.cache3"));  //6379
	}
	return instance;
}
 
Example 37
Project: wechat-mall   File: PoolUtil.java   View source code 5 votes vote down vote up
public static JedisPoolConfig defaultPoolConfig() {
    JedisPoolConfig config = new JedisPoolConfig();
    config.setMaxTotal(maxCount);
    config.setMaxIdle(maxIdle);
    config.setMaxWaitMillis(MaxWait);
    config.setTestOnBorrow(false);
    config.setTestOnReturn(false);
    return config;
}
 
Example 38
Project: RedisDirectory   File: TestLucene.java   View source code 5 votes vote down vote up
public void
testRedisDirectoryWithRemoteJedisPool() throws IOException {
    long start = System.currentTimeMillis();
    IndexWriterConfig indexWriterConfig = new IndexWriterConfig(new WhitespaceAnalyzer()).setOpenMode(IndexWriterConfig
            .OpenMode.CREATE);
    JedisPool jedisPool = new JedisPool(new JedisPoolConfig(), "10.97.19.55", 6379, Constants.TIME_OUT);
    RedisDirectory redisDirectory = new RedisDirectory(new JedisPoolStream(jedisPool));
    IndexWriter indexWriter = new IndexWriter(redisDirectory, indexWriterConfig);
    for (int i = 0; i < 5000000; i++) {
        indexWriter.addDocument(addDocument(i));
    }
    indexWriter.commit();
    indexWriter.close();
    redisDirectory.close();
    long end = System.currentTimeMillis();
    log.error("RedisDirectoryWithJedisPool consumes {}s!", (end - start) / 1000);
    start = System.currentTimeMillis();
    IndexSearcher indexSearcher = new IndexSearcher(DirectoryReader.open(new RedisDirectory(new JedisStream("localhost",
            6379))));
    int total = 0;
    for (int i = 0; i < 1000000; i++) {
        TermQuery key1 = new TermQuery(new Term("key1", "key" + i));
        TopDocs search = indexSearcher.search(key1, 10);
        total += search.totalHits;
    }
    System.out.println(total);
    end = System.currentTimeMillis();
    log.error("RedisDirectoryWithJedisPool search consumes {}ms!", (end - start));
}
 
Example 39
Project: RedisDirectory   File: TestLucene.java   View source code 5 votes vote down vote up
public void testRedisDirectoryWithJedisPool() throws IOException {
    long start = System.currentTimeMillis();
    IndexWriterConfig indexWriterConfig = new IndexWriterConfig(new WhitespaceAnalyzer()).setOpenMode(IndexWriterConfig
            .OpenMode.CREATE);
    //indexWriterConfig.setInfoStream(System.out);
    //indexWriterConfig.setRAMBufferSizeMB(2048);
    //LogByteSizeMergePolicy logByteSizeMergePolicy = new LogByteSizeMergePolicy();
    //logByteSizeMergePolicy.setMinMergeMB(1);
    //logByteSizeMergePolicy.setMaxMergeMB(64);
    //logByteSizeMergePolicy.setMaxCFSSegmentSizeMB(64);
    //indexWriterConfig.setRAMBufferSizeMB(1024).setMergePolicy(logByteSizeMergePolicy).setUseCompoundFile(false);
    //GenericObjectPoolConfig genericObjectPoolConfig = new GenericObjectPoolConfig();
    //获取连接等待时间
    //genericObjectPoolConfig.setMaxWaitMillis(3000);
    //10s超时时间
    JedisPool jedisPool = new JedisPool(new JedisPoolConfig(), "localhost", 6379, Constants.TIME_OUT);
    RedisDirectory redisDirectory = new RedisDirectory(new JedisPoolStream(jedisPool));
    IndexWriter indexWriter = new IndexWriter(redisDirectory, indexWriterConfig);
    for (int i = 0; i < 10000000; i++) {
        indexWriter.addDocument(addDocument(i));
    }
    indexWriter.commit();
    indexWriter.close();
    redisDirectory.close();
    long end = System.currentTimeMillis();
    log.error("RedisDirectoryWithJedisPool consumes {}s!", (end - start) / 1000);
    start = System.currentTimeMillis();
    IndexSearcher indexSearcher = new IndexSearcher(DirectoryReader.open(new RedisDirectory(new JedisStream("localhost",
            6379))));
    int total = 0;
    for (int i = 0; i < 10000000; i++) {
        TermQuery key1 = new TermQuery(new Term("key1", "key" + i));
        TopDocs search = indexSearcher.search(key1, 10);
        total += search.totalHits;
    }
    System.out.println(total);
    end = System.currentTimeMillis();
    log.error("RedisDirectoryWithJedisPool search consumes {}ms!", (end - start));
}
 
Example 40
Project: ace-cache   File: RedisConfig.java   View source code 5 votes vote down vote up
@Bean
public JedisPoolConfig constructJedisPoolConfig() {
    JedisPoolConfig config = new JedisPoolConfig();
    // 控制一个pool可分配多少个jedis实例,通过pool.getResource()来获取;
    // 如果赋值为-1,则表示不限制;如果pool已经分配了maxActive个jedis实例,则此时pool的状态为exhausted(耗尽)。
    config.setMaxTotal(Integer.parseInt(maxActive));
    // 控制一个pool最多有多少个状态为idle(空闲的)的jedis实例。
    config.setMaxIdle(Integer.parseInt(maxIdle));
    // 表示当borrow(引入)一个jedis实例时,最大的等待时间,如果超过等待时间,则直接抛出JedisConnectionException;
    config.setMaxWaitMillis(Integer.parseInt(maxWait));
    config.setTestOnBorrow(true);

    return config;
}