Java与redis交互、Jedis连接池JedisPool

匿名 (未验证) 提交于 2019-12-02 21:35:04

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();     }   }

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!