依賴jar包下載java
# Redis settings redis.host=192.168.208.153 redis.port=6379 redis.pass=1234 redis.timeout=10000 redis.maxIdle=300 redis.maxTotal=600 # 毫秒 redis.maxWaitMillis=1000
package com.zze.util; import java.io.IOException; import java.io.InputStream; import java.util.Properties; /** * 屬性文件加載工具類 * @author zze */ public class PropertyUtil { //加載property文件到io流裏面 public static Properties loadProperties(String propertyFile) { Properties properties = new Properties(); try { InputStream is = PropertyUtil.class.getClassLoader().getResourceAsStream(propertyFile); if (is == null) { is = PropertyUtil.class.getClassLoader().getResourceAsStream("properties/" + propertyFile); } properties.load(is); } catch (IOException e) { e.printStackTrace(); } return properties; } /** * 根據key值取得對應的value值 * * @param key * @return */ public static String getValue(String propertyFile, String key) { Properties properties = loadProperties(propertyFile); return properties.getProperty(key); } }
package com.zze.util; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; import java.util.Properties; @SuppressWarnings("all") public class RedisClient { //鏈接池 private static JedisPool jedisPool; static { try { Properties properties = PropertyUtil.loadProperties("redis.properties"); String host = properties.getProperty("redis.host"); String port = properties.getProperty("redis.port"); String pass = properties.getProperty("redis.pass"); String timeout = properties.getProperty("redis.timeout"); String maxIdle = properties.getProperty("redis.maxIdle"); String maxTotal = properties.getProperty("redis.maxTotal"); String maxWaitMillis = properties.getProperty("redis.maxWaitMillis"); String testOnBorrow = properties.getProperty("redis.testOnBorrow"); JedisPoolConfig config = new JedisPoolConfig(); //控制一個pool可分配多少個jedis實例,經過pool.getResource()來獲取; //若是賦值爲-1,則表示不限制;若是pool已經分配了maxActive個jedis實例,則此時pool的狀態爲exhausted(耗盡)。 config.setMaxTotal(Integer.parseInt(maxTotal)); //控制一個pool最多有多少個狀態爲idle(空閒的)的jedis實例。 config.setMaxIdle(Integer.parseInt(maxIdle)); //表示當borrow(引入)一個jedis實例時,最大的等待時間,若是超過等待時間,則直接拋出JedisConnectionException; config.setMaxWaitMillis(Long.parseLong(maxWaitMillis)); //在borrow一個jedis實例時,是否提早進行validate操做;若是爲true,則獲得的jedis實例均是可用的; config.setTestOnBorrow(Boolean.valueOf(testOnBorrow)); jedisPool = new JedisPool(config, host, Integer.parseInt(port), Integer.parseInt(timeout), pass); } catch (Exception e) { e.printStackTrace(); } } //獲取Redis資源 public synchronized static Jedis getJedis() { try { if (jedisPool != null) { Jedis jedis = jedisPool.getResource(); return jedis; } else { return null; } } catch (Exception e) { e.printStackTrace(); } return null; } //釋放redis資源 public synchronized static void releaseConn(Jedis jedis) { if (jedisPool != null) { jedis.close(); } } }
@Test public void test2(){ Jedis jedis = RedisClient.getJedis(); jedis.set("name", "張三"); String name = jedis.get("name"); System.out.println(name); }