Jedis使用のJedisPoolの使用

2517 ワード

**JedisPool**シーンを使用し、javaプログラムが単一のredisに接続する場合1.Jedis初期化、redis接続プールの構成、接続の取得
Jediscommands jediscommands;
JedisPool jedisPool;
JedisPoolConfig config = new JedisPoolConfig()
config.setMaxTotal(1024);
config.setMaxIdle(10);
config.setMaxWaitMillis(1000);
config.setTestOnBorrow(true);
config.setTestOnReturn(true);

String ip = "192.168.x.x"
int port = 6379
long timeOut = 2000
JedisPool jedisPool = new JedisPool(config,ip,port,timeOut)

Jedis jedis = jedisPool.getResource();
jediscommands = jedis

2.Jedis使用
jediscommands.set("testKey","hello");
String testResult = jediscommands.get("testKey");
logger.info("testResult:{}",testResult)

3.Jedis接続を解除し、finnallyで解除する
Jedis jedis = (jedis)jediscommands
if (jedis != null){
    jedis.release();
}

完全なコード:
package com.yj.test.javaBases.testJedis;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisCommands;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

public class TestJedis {
    public static final Logger logger = LoggerFactory.getLogger(TestJedis.class);
    // Jedispool
    JedisCommands jedisCommands;
    JedisPool jedisPool;
    JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
    String ip = "192.168.x.x";
    int port = 6379;
    int timeout = 2000;

    public TestJedis() {
        //    jedis
        //     
        jedisPoolConfig.setMaxTotal(1024);
        jedisPoolConfig.setMaxIdle(100);
        jedisPoolConfig.setMaxWaitMillis(100);
        jedisPoolConfig.setTestOnBorrow(false);//jedis       ,   
        jedisPoolConfig.setTestOnReturn(true);
        //    JedisPool
        jedisPool = new JedisPool(jedisPoolConfig, ip, port, timeout);
        //  
        Jedis jedis = jedisPool.getResource();

        jedisCommands = jedis;
    }

    public void setValue(String key, String value) {
        this.jedisCommands.set(key, value);
    }

    public String getValue(String key) {
        return this.jedisCommands.get(key);
    }

    public static void main(String[] args) {
        TestJedis testJedis = new TestJedis();
        testJedis.setValue("testJedisKey", "testJedisValue");
        logger.info("get value from redis:{}",testJedis.getValue("testJedisKey"));
    }

}