Redis入门很简单之四【初识Jedis】

使用Jedis提供的Java API对Redis进行操作,是Redis官方推崇的方式;并且,使用Jedis提供的对Redis的支持也最为灵活、全面;不足之处,就是编码复杂度较高。


[一]. 入门使用:
 下载Jedis的依赖包jedis-2.1.0.jar,然后将其添加到classpath下面。然后,即可进行编程:
  1. 定义连接:Redis暂时不要设置登录密码

Jedis jedis = new Jedis("192.168.142.12");

  2. 进行键值存储:

jedis.set("country", "China");

  3. 获取value值:

String country = jedis.get("country");

  4. 删除key: 

jedis.del("country");

[二]. 使用连接池:
  1. 添加依赖包commons-pool.jar,注意不要选择高版本,以免不必要的错误。
  2. 配置属性文件:redis.properties

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

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

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

  3. 加载属性文件:redis.properties

ResourceBundle bundle = ResourceBundle.getBundle("redis");

  4. 创建配置对象: 

JedisPoolConfig config = new JedisPoolConfig();
String host = bundle.getString("redis.host");
...
config.setMaxActive(Integer.valueOf(bundle.getString("redis.pool.maxActive")));
...
config.setTestOnBorrow(Boolean.valueOf(bundle.getString("redis.pool.testOnBorrow")));
...

  5. 创建Jedis连接池:

JedisPool pool = new JedisPool(config, host, port, timeout, password);

 [三]. 使用方式:   
 1. 从连接池获取Jedis对象:

Jedis jedis = pool.getResource();

 2. 基本操作:

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

3. 将Jedis对象归还给连接池:

pool.returnResource(jedis);

猜你喜欢

转载自hello-nick-xu.iteye.com/blog/2076890