package com..;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import redis.clients.jedis.Jedis;
public class RedisUtil {
// redis-server.exe redis.windows.conf --->啟動 redis
// redis-cli.exe -h 127.0.0.1 -p 6379 ---->操作 redis
public RedisUtil() {
}
private static Jedis jedis;// redis實例 jar包引入在最下方
private static String host;//地址
private static String port;//端口
private static String password;//授權密碼
private static String timeout;//超時時間:單位MS
private static String maxIdle;//最大空閑數:空閑鏈接數大於maxIdle時,將進行回收
private static String maxActive;//最大連接數:能夠同時建立的"最大鏈接個數"
private static String maxWait;//最大等待時間:單位ms
private static String testOnBorrow;//在獲取連接時,是否驗證有效性
static{
//加載properties配置文件
Properties properties = new Properties();
InputStream is = RedisUtil.class.getClassLoader().getResourceAsStream("redis_config.properties");
try {
properties.load(is);
} catch (IOException e) {
e.printStackTrace();
}
host = properties.getProperty("redis.single.host");
port = properties.getProperty("redis.single.port");
password = properties.getProperty("redis.password");
timeout = properties.getProperty("redis.timeout");
maxIdle = properties.getProperty("redis.maxIdle");
maxActive = properties.getProperty("redis.maxActive");
maxWait = properties.getProperty("redis.maxWait");
testOnBorrow = properties.getProperty("redis.testOnBorrow");
// 得到Jedis/JedisPool實例並且設置配置
jedis = new Jedis(host,Integer.parseInt(port),Integer.parseInt(timeout));
//jedis.auth("123456");//密碼
}
/**
* 寫入緩存
* @param key
* @param value
* @return
*/
public static boolean set (final String key,String value){
boolean result = false;
try {
jedis.set(key, value);
result = true;
} catch (Exception e) {
e.printStackTrace();
System.out.println("set cache error");
}
return result ;
}
/**
* 讀取緩存
* @param key
* @return
*/
public static String get(final String key) {
String result =null;
result = jedis.get(key);
return result;
}
/**
* 刪除key對應的value
* @param key
*/
public static void del(final String key) {
if(key!=null&&key.length()>=1&&!key.equals("")&&jedis.exists(key)){
jedis.del(key);
}
}
/**
* 判斷緩存中是否有key對應的value
* @param key
* @return
*/
public static boolean exists(final String key) {
return jedis.exists(key);
}
/**
* 寫入緩存(規定緩存時間)
* @param key
* @param value
* @param expireSecond
* @return
*/
public static boolean set(final String key,String value,Long expireSecond) {
boolean result = false;
try {
// NX代表不存在才set,EX代表秒,PX代表毫秒
jedis.set(key, value, "NX", "EX", expireSecond);
result = true;
} catch (Exception e) {
e.printStackTrace();
System.out.println("set cache error on time");
}
return result;
}
/**
* <p>
* 通過key向list頭部添加字符串
* </p>
*
* @param key
* @param strs
* 可以使一個string 也可以使string數組
* @return 返回list的value個數
*/
public static Long lpush(String key, String... strs) {
Long res = null;
res = jedis.lpush(key, strs);
return res;
}
}
<!-- 引入 jedis 包驅動: -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>