JAVA中使用Jedis操作Redis
阿新 • • 發佈:2022-04-29
redis安裝看這裡:https://my.oschina.net/u/2486137/blog/1541190
需要的jar:commons-pool2 ,redis.clients
①. 進入這裡檢視操作redis的客戶端語言及支援的操作方式: https://redis.io/clients
②.我選擇的是jedis ,這裡對jedis進行了一個小小的封裝,經過簡單的測試,挺好用的.
這裡儲存物件基本上都是以位元組陣列儲存的,所以寫了個序列化和反序列化的util
/** * 序列化 * @param t * @return * @throws Exception */ public static <T> byte[] serializable(T t) throws Exception { ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeObject(t); byte[] b = bos.toByteArray(); bos.close(); oos.close(); return b; } /** * 反序列化 * @param b * @return * @throws Exception */ @SuppressWarnings("unchecked") public static <T> T unserializable(byte[] b) throws Exception { ByteArrayInputStream bis = new ByteArrayInputStream(b); ObjectInputStream ois = new ObjectInputStream(bis); T t = (T) ois.readObject(); bis.close(); ois.close(); return t; }
③.連線池建立:
private static final String CACHE_KEY = "cache-"; private static Jedis jedis; private static JedisPool JEDIS_POOL = null; static { JedisPoolConfig config = new JedisPoolConfig(); config.setMaxIdle(RedisConf.MAX_IDLE); config.setMaxTotal(RedisConf.MAX_TOTAL); config.setMaxWaitMillis(RedisConf.MAX_WAIT); config.setMinIdle(RedisConf.MIN_IDLE); JEDIS_POOL = new JedisPool(config, RedisConf.HOST, RedisConf.PORT, RedisConf.TIMEOUT, RedisConf.AUTH); // 獲取jredis例項 getJRedis(); }
④.操作key-value鍵值對
public <K extends Serializable, V extends Serializable> void putMap(String key, Map<K, V> map) throws Exception { if (StringUtils.isEmpty(key) || map.size() < 1) { return; } if (jedis == null) getJRedis(); jedis.set((CACHE_KEY + key).getBytes(), SerializableUtil.serializable(map)); // jedis.hmset(key.getBytes(), serializable(map)); } public <K extends Serializable, V extends Serializable> Map<K, V> getMap(String key) throws Exception { if (StringUtils.isEmpty(key)) { throw new NullPointerException("key empty!"); } if (jedis == null) getJRedis(); if (!jedis.exists((CACHE_KEY + key).getBytes())) { return null; } return SerializableUtil.unserializable(jedis.get((CACHE_KEY + key).getBytes())); }
Map map = new HashMap();
map.put("age", 12);
map.put("name", "tony");
redis.put("map", map);
System.out.println(redis.getMap("map"));
//測試結果:
{age=12, name=tony}
⑤.操作一個物件:
/**
* 新增一個物件
*
* @param key
* @param t
* @throws Exception
*/
public <T extends Serializable> void putObject(String key, T t) throws Exception {
if (StringUtils.isEmpty(key) || t == null) {
return;
}
if (jedis == null) getJRedis();
jedis.set((CACHE_KEY + key).getBytes(), SerializableUtil.serializable(t));
}
/**
* 獲取物件
*
* @param key
* @return
* @throws Exception
*/
@Deprecated
public <T extends Serializable> T getObject(String key) throws Exception {
if (StringUtils.isEmpty(key)) {
throw new NullPointerException("key empty!");
}
if (jedis == null) getJRedis();
return SerializableUtil.unserializable(jedis.get((CACHE_KEY + key).getBytes()));
}
redis.putObject("person", new Person(1, "timor", 19L, "male", new Date()));
System.out.println(redis.getObject("person"));
//測試結果
Person [id=1, name=timor, age=19, gender=male, birthday=Thu Sep 21 16:00:50 CST 2017]
⑥.操作一個list
/**
* 新增一個List集合
*
* @param key
* @param list
* @throws Exception
*/
@Deprecated
public <S extends Serializable> void putList(String key, List<S> list) throws Exception {
if (StringUtils.isEmpty(key) || list.size() < 1) {
return;
}
if (jedis == null) getJRedis();
jedis.set((CACHE_KEY + key).getBytes(), SerializableUtil.serializable(list));
}
@Deprecated
public <S extends Serializable> List<S> getList(String key) throws Exception {
if (StringUtils.isEmpty(key)) {
throw new NullPointerException("key empty!");
}
if (jedis == null) getJRedis();
return SerializableUtil.unserializable(jedis.get((CACHE_KEY + key).getBytes()));
}
List<String> list = new ArrayList<String>();
list.add("a");
list.add("b");
list.add("c");
redis.putList("my-list", list);
System.out.println(redis.getList("my-list"));
//測試結果
[a, b, c]
⑦.操作set:
/**
* 新增一個Set集合
*
* @param key
* @param set
* @throws Exception
*/
@Deprecated
public <S extends Serializable> void putSet(String key, Set<S> set) throws Exception {
if (StringUtils.isEmpty(key) || set.size() < 1) {
return;
}
if (jedis == null) getJRedis();
jedis.set((CACHE_KEY + key).getBytes(), SerializableUtil.serializable(set));
// for (byte[] b : serializable(set)) {
// jedis.sadd(key.getBytes(), b);
// }
}
@Deprecated
public <S extends Serializable> Set<S> getSet(String key) throws Exception {
if (StringUtils.isEmpty(key)) {
throw new NullPointerException("key empty!");
}
if (jedis == null) getJRedis();
return SerializableUtil.unserializable(jedis.get((CACHE_KEY + key).getBytes()));
}
RedisUtil redis = new RedisUtil();
Set<String> set = new HashSet<String>();
set.add("1");
set.add("2");
set.add("3");
redis.putSet("my-set", set);
System.out.println(redis.getSet("my-set"));
//測試結果
[3, 2, 1]
⑧. 上述寫的過於麻煩,這裡把上述全部廢棄不再使用,下面是完整的程式碼:
private static final String CACHE_KEY = "cache-";
private static Jedis jedis;
private static JedisPool JEDIS_POOL = null;
static {
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxIdle(RedisConf.MAX_IDLE);
config.setMaxTotal(RedisConf.MAX_TOTAL);
config.setMaxWaitMillis(RedisConf.MAX_WAIT);
config.setMinIdle(RedisConf.MIN_IDLE);
JEDIS_POOL = new JedisPool(config, RedisConf.HOST, RedisConf.PORT, RedisConf.TIMEOUT,
RedisConf.AUTH);
// 獲取jredis例項
getJRedis();
}
/**
* 根據key-獲取值
* @param key
* @return
* @throws Exception
*/
public <T extends Serializable> T get(String key) throws Exception {
if (StringUtils.isEmpty(key)) return null;
if (jedis == null) getJRedis();
if (!jedis.exists((CACHE_KEY + key).getBytes())) return null;
T t = SerializableUtil.unserializable(jedis.get((CACHE_KEY + key).getBytes()));
return t;
}
/**
* 非持久化操作
* @param <T>
*
* @param key
* @param t
* @param seconds 過期時間
* @throws Exception
*/
public <T> void put(String key, T t ,int seconds) throws Exception {
if (StringUtils.isEmpty(key) || t == null || seconds < 1) {
return;
}
if (jedis == null) getJRedis();
jedis .setex((CACHE_KEY + key).getBytes(), seconds, SerializableUtil.serializable(t));
}
/**
* 持久化操作
* @param key
* @param t
* @throws Exception
*/
public <T> void put(String key, T t) throws Exception {
if (StringUtils.isEmpty(key) || t == null) {
return;
}
if (jedis == null) getJRedis();
jedis.set((CACHE_KEY + key).getBytes(), SerializableUtil.serializable(t));
}
/**
* 刪除
* @param key
*/
public void remove(String key) {
jedis.del(key.getBytes());
}
private synchronized static void getJRedis() {
if (JEDIS_POOL == null) {
return;
}
jedis = JEDIS_POOL.getResource();
}
public interface RedisConf {
String HOST = "redis";
Integer PORT = 6379;
String AUTH = "123";// 密碼 ,redis-conf檔案中的 requirepass屬性後的值即為密碼
// 連線的最大數目,預設值為8;
// 如果賦值為-1,則表示不限制;如果pool已經分配了maxActive個jedis例項,則此時pool的狀態為exhausted(耗盡)。
Integer MAX_TOTAL = 100;
// 等待可用連線的最大時間,單位毫秒,預設值為-1,表示永不超時。
// 如果超過等待時間,則直接丟擲JedisConnectionException;
Integer MAX_WAIT = -1;
// 最大空閒的jedis例項個數,預設值也是8
Integer MAX_IDLE = 30;
// 最小連線數
Integer MIN_IDLE = 50;
// 連線超時時間
Integer TIMEOUT = 5000;
}
轉載請註明出處謝謝!