Skip to content

Instantly share code, notes, and snippets.

@mp911de
Created October 30, 2017 20:35
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mp911de/c1e6c7cd8c2adae2c7549eeb3b4797e2 to your computer and use it in GitHub Desktop.
Save mp911de/c1e6c7cd8c2adae2c7549eeb3b4797e2 to your computer and use it in GitHub Desktop.
Create Redis Connections with pooling
/*
* Copyright 2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.DirectFieldAccessor;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.lettuce.DefaultLettucePool;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
/**
* @author Mark Paluch
*/
public class Standalone {
public static void main(String[] args) throws Exception {
GenericObjectPoolConfig config = new GenericObjectPoolConfig();
config.setMinIdle(8);
config.setTestWhileIdle(true);
config.setMinIdle(8);
config.setMaxIdle(10);
config.setMaxTotal(128);
config.setMinEvictableIdleTimeMillis(8000);
config.setTimeBetweenEvictionRunsMillis(3000);
DefaultLettucePool pool = new DefaultLettucePool("localhost", 6379, config);
pool.afterPropertiesSet();
LettuceConnectionFactory lcf = new LettuceConnectionFactory(pool);
lcf.afterPropertiesSet();
DirectFieldAccessor accessor = new DirectFieldAccessor(pool);
GenericObjectPool p = (GenericObjectPool) accessor.getPropertyValue("internalPool");
List<RedisConnection> conn = new ArrayList<>();
for (int i = 0; i < 72; i++) {
conn.add(lcf.getConnection());
}
conn.forEach(c -> c.multi());
System.out.println("ping: active: " + p.getNumActive());
Thread.sleep(1000);
conn.forEach(c -> c.close());
while (true) {
System.out.println("ping: active: " + p.getNumActive() + ", idle: " + p.getNumIdle());
Thread.sleep(1000);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment