下面列出了org.springframework.boot.actuate.health.HealthIndicator#redis.clients.jedis.JedisPool 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public void run() {
JedisPool pool = Application.getCommonCache().getJedisPool();
try (Jedis jedis = pool.getResource()) {
if (useTopic) {
jedis.subscribe(new TopicProducer(), RedisQueueObserver.QUEUE_NAME);
System.out.println("subscribe ...");
}
else {
while (true) {
// BLOCK ...
List<String> datas = jedis.blpop(0, RedisQueueObserver.QUEUE_NAME);
System.out.println("Reviced queue data : " + datas);
}
}
}
}
@Test
public void testJedisPool() {
JedisPool pool = new JedisPool(config, host);
Jedis jedis = pool.getResource();
byte[] key = "hello ".getBytes();
byte[] value = "world".getBytes();
long startM = 0l, endM = 0l;
startM = System.currentTimeMillis();
for ( int i=0; i<max; i++ ) {
key[key.length-1] = (byte)(i&0xFF);
jedis.set(key, value);
jedis.del(key);
}
endM = System.currentTimeMillis();
System.out.println("Original Jedis loop " + max + " perform: " + (endM-startM));
}
private void add(String client,String host,int maxTotal,int maxIdle)
{
logger.info("Adding Redis pool for "+client+" at "+host+" maxTotal "+maxTotal+" maxIdle "+maxIdle);
JedisPoolConfig poolConfig = new JedisPoolConfig();
poolConfig.setMaxTotal(maxTotal); // maximum active connections
poolConfig.setMaxIdle(maxIdle); // maximum idle connections
JedisPool pool = new JedisPool(poolConfig, host);
JedisPool existing = pools.get(client);
pools.put(client, pool);
if (existing != null)
{
logger.warn("Attempting to close previous pool for "+client);
existing.destroy();
}
}
private Jedis getJedis(String redisKey) {
try {
JedisPoolPack jedisPoolPack = jedisPoolMap.get(redisKey);
JedisPool jedisPool = jedisPoolPack.getJedisPool();
if (jedisPool == null) {
LOGGER.error("jedis pool not found. key={} existKeys={}", redisKey, jedisPoolMap.keySet());
return null;
}
Jedis jedis = jedisPool.getResource();
jedis.select(jedisPoolPack.getDbIndex());
return jedis;
} catch (Exception e) {
LOGGER.error("", e);
}
return null;
}
@Before
public void setUp() throws IOException {
initMocks(this);
final SecureRandom 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);
}
public void collectStats() {
if (pool instanceof PjedisPool) {
try (Jedis jedis = ((PjedisPool)pool).getResource()) {
constantsCollect("Host", jedis.getClient().getHost());
constantsCollect("Port", jedis.getClient().getPort() + "");
}
}
if (pool instanceof JedisPool) {
try (Jedis jedis = ((JedisPool)pool).getResource()) {
constantsCollect("Host", jedis.getClient().getHost());
constantsCollect("Port", jedis.getClient().getPort() + "");
}
}
gaugeCollect("NumActive", pool.getNumActive());
gaugeCollect("NumIdle", pool.getNumIdle());
gaugeCollect("NumWaiters", pool.getNumWaiters());
gaugeCollect("MaxBorrowWaitTimeMillis", pool.getMaxBorrowWaitTimeMillis());
gaugeCollect("MeanBorrowWaitTimeMillis", pool.getMeanBorrowWaitTimeMillis());
infoCollect();
}
private JedisPool createJedisPool() throws IOException {
String host;
Integer port;
config.load(
Thread.currentThread()
.getContextClassLoader()
.getResourceAsStream("application.properties"));
host = config.getProperty("redis.host");
port = Integer.valueOf(config.getProperty("redis.port", "6379"));
JedisPoolConfig poolConfig = new JedisPoolConfig();
// Default : 8, consider how many concurrent connections into Redis you will need under load
poolConfig.setMaxTotal(128);
return new JedisPool(poolConfig, host, port);
}
@Test
public void test2() throws InterruptedException {
JedisPool jp=new JedisPool("127.0.0.1",6379);
final RedisDistributedLockTemplate template=new RedisDistributedLockTemplate(jp);
LimitRule limitRule=new LimitRule();
limitRule.setSeconds(1);
limitRule.setLimitCount(5);
limitRule.setLockCount(7);
limitRule.setLockTime(2);
AccessSpeedLimit accessSpeedLimit=new AccessSpeedLimit(jp);
SimpleDateFormat sdf=new SimpleDateFormat(" mm:ss");
while(true){
//10.0.0.1这个ip每1秒钟最多访问5次if块内代码.1秒超过10次后,锁定2秒,2秒内无法访问.
if(accessSpeedLimit.tryAccess("10.0.0.1",limitRule)){
System.out.println("yes"+sdf.format(new Date()));
}else{
System.out.println("no"+sdf.format(new Date()));
}
Thread.sleep(100);
}
}
private SlackTestConfig(SlackConfig config) {
this.config = config;
CONFIG.getHttpClientResponseHandlers().add(new HttpResponseListener() {
@Override
public void accept(State state) {
String json = GsonFactory.createSnakeCase(CONFIG).toJson(getMetricsDatastore().getAllStats());
log.debug("--- (MethodsStats) ---\n" + json);
}
});
// Testing with Redis
String redisEnabled = System.getenv(Constants.SLACK_SDK_TEST_REDIS_ENABLED);
if (redisEnabled != null && redisEnabled.equals("1")) {
// brew install redis
// redis-server /usr/local/etc/redis.conf --loglevel verbose
JedisPool jedis = new JedisPool("localhost");
CONFIG.getMethodsConfig().setMetricsDatastore(new RedisMetricsDatastore("test", jedis));
}
}
/**
* @param host
* redis.server.ip
* @param port
* redis.server.port
*/
public JedisConnectionPool(String h, int p) throws Exception {
if (jedisPoolA == null) {
host = h;
port = p;
try {
JedisPool pool = initJedisPool(host, port);
if (pool != null) {
jedisPoolA = pool;
} else {
throw new Exception("Redis Connection Error - " + h + ":" + p);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
@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"));
jedis0.close();
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"));
jedis1.close();
pool1.destroy();
assertTrue(pool1.isClosed());
}
/**
* Gets the connection from the connection pool and adds the wrapper catch/finally block for the
* given function.
*
* This helper method saves the trouble of dealing with redis connection. When we got
* JedisConnectionException, we will discard this connection. Otherwise, we return the connection
* to the connection pool.
*
* @param jedisPool Jedis connection pool
* @param redisDBNum Redis DB number (index) (if redisDBNum == -1, don't select a DB )
* @param func The function to execute inside the catch/finally block.
* @return A Resp object, which is the return value of wrapped function.
*/
public static <Resp> Resp executeWithConnection(JedisPool jedisPool,
int redisDBNum,
Function<Jedis, Resp> func) {
Preconditions.checkNotNull(jedisPool);
Preconditions.checkNotNull(func);
Jedis conn = null;
boolean gotJedisConnException = false;
try {
conn = jedisPool.getResource();
selectRedisDB(conn, redisDBNum);
return func.apply(conn);
} catch (JedisConnectionException e) {
jedisPool.returnBrokenResource(conn);
gotJedisConnException = true;
throw e;
} finally {
if (conn != null && !gotJedisConnException) {
jedisPool.returnResource(conn);
}
}
}
@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());
jedis.close();
assertEquals(1, pool.getNumActive());
jedis2.close();
assertEquals(0, pool.getNumActive());
pool.destroy();
}
public static byte[] getKeyValue(JedisPool jedisPool, final byte[] key) {
return execute(jedisPool, new JedisCallback<byte[]>() {
@Override
public byte[] doInJedis(Jedis jedis) {
Map<byte[], byte[]> fieldValueMap = jedis.hgetAll(key);
List<Map.Entry<byte[], byte[]>> entries = new ArrayList<Map.Entry<byte[], byte[]>>(fieldValueMap.entrySet());
Collections.sort(entries, new Comparator<Map.Entry<byte[], byte[]>>() {
@Override
public int compare(Map.Entry<byte[], byte[]> entry1, Map.Entry<byte[], byte[]> entry2) {
return (int) (ByteUtils.bytesToLong(entry1.getKey()) - ByteUtils.bytesToLong(entry2.getKey()));
}
});
byte[] content = entries.get(entries.size() - 1).getValue();
return content;
}
});
}
@Override
@Deprecated
public Jedis getJedis() {
try {
JedisPool pool = _jedis.get(conf.getConf(null, "redis.host"));
if (pool == null) return null;
return pool.getResource();
} catch (Exception e) {
LOG.error(e.getMessage(), e);
}
return null;
}
@PreDestroy
public void tearDown()
{
for (Map.Entry<HostAddress, JedisPool> entry : jedisPoolCache.asMap().entrySet()) {
try {
entry.getValue().destroy();
}
catch (Exception e) {
log.warn(e, "While destroying JedisPool %s:", entry.getKey());
}
}
}
public RedisBungeeConfiguration(JedisPool pool, Configuration configuration) {
this.pool = pool;
this.serverId = configuration.getString("server-id");
this.registerBungeeCommands = configuration.getBoolean("register-bungee-commands", true);
List<String> stringified = configuration.getStringList("exempt-ip-addresses");
ImmutableList.Builder<InetAddress> addressBuilder = ImmutableList.builder();
for (String s : stringified) {
addressBuilder.add(InetAddresses.forString(s));
}
this.exemptAddresses = addressBuilder.build();
}
public Metrics() throws URISyntaxException {
if(System.getenv("REDIS_URL") == null) {
throw new IllegalArgumentException("No REDIS_URL is set!");
}
URI redisUri = new URI(System.getenv("REDIS_URL"));
pool = new JedisPool(redisUri);
}
@Before
public void setUp() throws Exception {
port = getPort();
redisServer = RedisServer.builder()
.port(port)
.build();
redisServer.start();
jedisPool = new JedisPool(HOST, port);
scheduler = new StdSchedulerFactory(schedulerConfig(HOST, port)).getScheduler();
scheduler.start();
}
synchronized void tryUpdate(RedisConfiguration newConfig) {
if (Objects.equals(newConfig, config)) return;
shutdown();
config = newConfig;
for (String addr : config.getHosts()) {
String[] tokens = StringUtils.split(addr, ':');
String host = tokens[0];
int port = Integer.parseInt(tokens[1]);
jedisPools.add(new JedisPool(config.getJedisPool(), host, port, config.getTimeout(), config.getPassword()));
}
}
/**
* 为Redis数据库中的商品赋值
*
* @param arr
* String 抢购商品数组
* @param num
* int 商品库存
*/
private static void assignment(String[] arr, int num, JedisPool jedisPool) {
// 获得连接
Jedis jedis = jedisPool.getResource();
boolean flag = false;
for (int i = 0; i < arr.length; i++) {
jedis.set(arr[i], num + "");
}
}
/**
* 初始化Redis连接池
*/
private static void initialPool() {
try {
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxTotal(MAX_ACTIVE);
config.setMaxIdle(MAX_IDLE);
config.setMaxWaitMillis(MAX_WAIT);
config.setTestOnBorrow(TEST_ON_BORROW);
jedisPool = new JedisPool(config, IP, PORT, TIMEOUT);
} catch (Exception e) {
LOGGER.error("First create JedisPool error : " + e);
}
}
private JedisPool createConsumer() {
String pwd = password;
if (StringUtils.isEmpty(pwd)) {
pwd = null;
}
return new JedisPool(jedisPoolConfig, host, port, timeout, pwd, database);
}
/**
* 제디스 연결풀 생성을 위한 도우미 클래스 내부 생성자. 싱글톤 패턴이므로 외부에서 호출할 수 없다.
*/
private JedisHelper() {
GenericObjectPoolConfig config = new GenericObjectPoolConfig();
config.setMaxTotal(20);
config.setBlockWhenExhausted(true);
this.pool = new JedisPool(config, REDIS_HOST, REDIS_PORT);
}
private static void initPool() {
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxTotal(maxTotal);
config.setMaxIdle(maxIdle);
config.setTestOnBorrow(testOnBorrow);
config.setBlockWhenExhausted(true);
config.setMaxWaitMillis(maxWait);
pool = new JedisPool(config, redisIP, redisPort, 1000 * 2);
}
public static JedisPool getInstance() {
if (jedisPool == null) {
synchronized (JedisUtil.class) {
if (jedisPool == null) {
jedisPool = SpringContextHolder.getBean("jedisPool");
}
}
}
return jedisPool;
}
@Test
public void returnResourceShouldResetState() {
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");
Transaction t = jedis.multi();
t.set("hello", "world");
} finally {
jedis.close();
}
Jedis jedis2 = pool.getResource();
try {
assertTrue(jedis == jedis2);
assertEquals("jedis", jedis2.get("hello"));
} finally {
jedis2.close();
}
pool.destroy();
assertTrue(pool.isClosed());
}
private void getRedisConnection() {
JedisPoolConfig poolConfig = new JedisPoolConfig();
pool = new JedisPool(poolConfig, URI.create(conf.uri), conf.connectionTimeout * MILLIS); // connectionTimeout value is in seconds
String userInfo = URI.create(conf.uri).getUserInfo();
jedis = pool.getResource();
if (userInfo != null && userInfo.split(":", 2).length > 0) {
jedis.clientSetname(userInfo.split(":", 2)[0]);
}
jedis.ping();
}
public synchronized boolean init() {
if (isInited)
return Boolean.TRUE;
try {
String host = RedisProperties.host;
String port = RedisProperties.port;
String password = RedisProperties.password;
String maxActive = RedisProperties.maxActive;
String maxIdle = RedisProperties.maxIdle;
String minIdle = RedisProperties.minIdle;
String maxWait = RedisProperties.maxWait;
String minEvictableIdleTimeMillis = RedisProperties.minEvictableIdleTimeMillis;
String timeBetweenEvictionRunsMillis = RedisProperties.timeBetweenEvictionRunsMillis;
poolConfig.setMaxTotal(Integer.parseInt(StringUtils.isBlank(maxActive) ? "1000" : maxActive.trim()));
poolConfig.setMaxIdle(Integer.parseInt(StringUtils.isBlank(maxIdle) ? "1000" : maxIdle.trim()));
poolConfig.setMinIdle(Integer.parseInt(StringUtils.isBlank(minIdle) ? "10" : minIdle.trim()));
poolConfig.setMaxWaitMillis(Long.parseLong(StringUtils.isBlank(maxWait) ? "20000" : maxWait.trim()));
if (StringUtils.isNotBlank(minEvictableIdleTimeMillis)) // 设定多长时间视为失效链接
poolConfig.setMinEvictableIdleTimeMillis(Integer.parseInt(minEvictableIdleTimeMillis.trim()));
if (StringUtils.isNotBlank(timeBetweenEvictionRunsMillis)) // 设定每隔多长时间进行有效检查与上面参数同时使用
poolConfig.setTimeBetweenEvictionRunsMillis(Integer.parseInt(timeBetweenEvictionRunsMillis.trim()));
jedisPool = new JedisPool(poolConfig, host, Integer.parseInt(port.trim()), timeout, password);
isInited = Boolean.TRUE;
return Boolean.TRUE;
} catch (Exception e) {
logger.error(" Initialization Redis Exception :", e);
}
return Boolean.FALSE;
}
public void delString(String key) {
JedisPool instance = this.instance();
if (StringUtils.isEmpty(key) || instance == null) return;
Jedis jedis = instance.getResource();
jedis.del(key); // 返回值成功是 1
jedis.close();
}