您的位置:首页 > 数据库 > Redis

Redis+linux自定义池化(三)

2016-04-13 21:01 483 查看
Redis+linux自定义池化(三)


一,导入的包:

1,jedis-2.8.0.jar

2,commons-collections-3.2.2.jar

3,commons-logging.jar

4,commons-pool2-2.4.2.jar

二,池化:就是创建一个redis连接池,有利于加快redis的访问速度。

1,先创建一个redis.properties文件里面存放池的值

#最大分配的对象数

redis.pool.maxActive=1024

#最大能够保持idel状态的对象数

redis.pool.maxIdle=200

#当池内没有返回对象时,最大等待时间

redis.pool.maxWait=1000

#当调用borrow Object方法时,是否进行有效性检查

redis.pool.testOnBorrow=true

#当调用return Object方法时,是否进行有效性检查

redis.pool.testOnReturn=true

#IP地址

redis.ip=192.168.14.215

#port 端口号

redis.port=6379

2,创建一个MyProperties,用来加载池中的值。
import java.io.IOException;
import java.util.Properties;

public class MyProperties extends Properties {
private static MyProperties mp;

private MyProperties(){
try {
this.load(MyProperties.class.getClassLoader().getResourceAsStream("redis.properties"));
} catch (IOException e) {
e.printStackTrace();
}
}

public static MyProperties getInstance(){
if(mp==null){
mp=new MyProperties();
}
return mp;
}

}

3,测试:因为池只要加载一次,所有将其静态化  单列
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

public class Test {
private static JedisPool pool;
//池化配置
static{
JedisPoolConfig config=new JedisPoolConfig();
//通过MyProperties的实列取到最大值。。。
config.setMaxTotal(Integer.valueOf(MyProperties.getInstance().getProperty("redis.pool.maxActive")));
config.setMaxIdle(Integer.valueOf(MyProperties.getInstance().getProperty("redis.pool.maxIdle")));
config.setMaxWaitMillis(Integer.valueOf(MyProperties.getInstance().getProperty("redis.pool.maxWait")));
config.setTestOnBorrow(Boolean.valueOf(MyProperties.getInstance().getProperty("redis.pool.testOnBorrow")));
config.setTestOnReturn(Boolean.valueOf(MyProperties.getInstance().getProperty("redis.pool.testOnReturn")));
pool=new JedisPool(config,MyProperties.getInstance().getProperty("redis.ip"),(Integer.valueOf(MyProperties.getInstance().getProperty("redis.port"))));
}

public static void main(String[] args) {
Jedis jedis= pool.getResource(); //从池中取到资源,即获得一个连接。
String keys="name";
jedis.del(keys);
jedis.set(keys, "yjl");
String value=jedis.get(keys);
System.out.println(value);
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: