java redis pool_Java与redis交互、Jedis连接池JedisPool

本文介绍了Java通过Jedis库与Redis进行交互的基本用法,包括单次连接操作和使用JedisPool连接池的方式。在JedisPool中,详细展示了如何配置连接池参数,并提供了从配置文件加载参数的方法,以实现更灵活的管理。
摘要由CSDN通过智能技术生成

Java与redis交互比较常用的是Jedis。

先导入jar包: commons-pool2-2.3.jar

jedis-2.7.0.jar

基本使用:

public class RedisTest1 { public static void main(String[] args) { Jedis jedis = new Jedis("localhost",6379); jedis.set("username","chichung"); jedis.close(); } }

JedisPool连接池

基本使用如下:

public class RedisTest2 { public static void main(String[] args) { // 比较特殊的是,redis连接池的配置首先要创建一个连接池配置对象 JedisPoolConfig config = new JedisPoolConfig(); // 当然这里还有设置属性的代码 // 创建Jedis连接池对象 JedisPool jedisPool = new JedisPool(config,"localhost",6379); // 获取连接 Jedis jedis = jedisPool.getResource(); // 使用 // 关闭,归还连接到连接池 jedis.close(); } }

一般可以抽取出来作为一个工具类使用:

例如有一个配置文件jedis.properties。

里面的内容如下: host=127.0.0.1

port=6379

maxTotal=50

maxIdle=10

工具类代码如下:

package com.chichung.redis; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; import java.io.IOException; import java.io.InputStream; import java.util.Properties; public class JedisPoolUtils { private static JedisPool jedisPool; static { InputStream is = JedisPoolUtils.class.getClassLoader().getResourceAsStream("jedis.properties"); Properties properties = new Properties(); try { properties.load(is); } catch (IOException e) { e.printStackTrace(); } JedisPoolConfig config = new JedisPoolConfig(); config.setMaxTotal(Integer.parseInt(properties.getProperty("maxTotal"))); config.setMaxIdle(Integer.parseInt(properties.getProperty("maxIdle"))); jedisPool = new JedisPool(config, properties.getProperty("host"), Integer.parseInt(properties.getProperty("port"))); } public static Jedis getJedis(){ return jedisPool.getResource(); } }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值