** 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"));
}
}