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

Jedis初识

2016-09-04 16:43 211 查看

一 基本概念

 Jedis是redis的java版本客户端的实现

 依赖架包

  jedis-2.6.0.jar

  commons-pool.jar(连接池依赖架包)

二 Jedis的基本使用

 1、直接使用

Jedis jedis = new Jedis("127.0.0.1");  //定义连接
jedis.auth("password");//授权
jedis.set("country", "China");  //进行键值存储
String country = jedis.get("country");  //获取value的值
jedis.del("country"); //删除key


 2、使用连接池

  1)配置属性文件:redis.properties

redis.host=127.0.0.1            #Redis服务器地址
redis.port=6379                 #服务端口
redis.timeout=3000              #超时时间:单位ms
redis.password=nick123          #授权密码

#最大连接数:能够同时建立的“最大链接个数”
redis.pool.maxActive=200
#最大空闲数:空闲链接数大于maxIdle时,将进行回收
redis.pool.maxIdle=20
#最小空闲数:低于minIdle时,将创建新的链接
redis.pool.minIdle=5
#最大等待时间:单位ms
redis.pool.maxWait=3000

#使用连接时,检测连接是否成功
redis.pool.testOnBorrow=true
#返回连接时,检测连接是否成功
redis.pool.testOnReturn=true


  2)加载属性文件

//ResourceBundle是Java中用来读取properties文件的类
ResourceBundle bundle = ResourceBundle.getBundle("redis");


  3)创建配置对象

JedisPoolConfig config = new JedisPoolConfig();
Integer maxActive = Integer.valueOf(
  bundle.getString("redis.pool.maxActive"));
...
config.setMaxTotal(maxActive);
config.setMaxIdle(maxIdel);
config.setMaxWaitMillis(maxWait);
config.setTestOnBorrow(testOnBorrow);
config.setTestOnReturn(testOnReturn);
config.setTestWhileIdle(true);


  4)创建Jedis连接池

String host = bundle.getString("redis.host");
Integer port = Integer.valueOf(
  bundle.getString("redis.host"));
...
JedisPool pool = new JedisPool(config,host,
  port,timeout,password);


  5)从连接池获取Jedis对象

Jedis jedis = pool.getResource();


  6)具体操作

jedis.set("province", "beijing");
String province = jedis.get("province");
jedis.del("province");


  7)将Jedis对象归还连接池

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