在上一篇文章中已經講了redis的spring配置,這篇將會描述redis在java項目中的使用。
redis存儲形式都是key-value(鍵值對),按照存儲的內容分為兩種,一種是存簡單數據,即數字,字符串等,可以用string-value的形式存儲;另一種是存對象、集合等,最好用序列化的方式來存儲。
1、存儲簡單數據
try { Jedis jedis = new Jedis(); jedis.set("name", "JackGSmith"); } catch (Exception e) { //如果緩存連不上,則不處理 System.out.println("登錄無法更新該用戶緩存"); }
從redis緩存中獲取key為“name”的值,使用jedis.get("name"),用一個String變量接收即可。
2、存儲對象、集合
存對象集合用序列化的方式存儲,用反序列化的方式取值。存儲的key和value都是轉化成字節碼的形式。
先定義一個抽象類:SerializeTranscoder.java,代碼如下:
package cn.com.taiji.sample.utils; import java.io.Closeable; import java.io.IOException; public abstract class SerializeTranscoder { public abstract byte[] serialize(Object value); public abstract Object deserialize(byte[] in) throws IOException; public void close(Closeable closeable) { if (closeable != null) { try { closeable.close(); } catch (Exception e) { e.printStackTrace(); } } } }
再建一個序列化的類,ObjectTranscoder.java,繼承上面這個抽象類,該類是用來序列化存儲對象用的,代碼如下:
package cn.com.taiji.sample.utils; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; public class ObjectTranscoder<M extends Serializable> extends SerializeTranscoder{ @SuppressWarnings("unchecked") @Override public byte[] serialize(Object value) { if (value == null) { throw new NullPointerException("Can't serialize null"); } byte[] result = null; ByteArrayOutputStream bos = null; ObjectOutputStream os = null; try { bos = new ByteArrayOutputStream(); os = new ObjectOutputStream(bos); M m = (M) value; os.writeObject(m); os.close(); bos.close(); result = bos.toByteArray(); } catch (IOException e) { throw new IllegalArgumentException("Non-serializable object", e); } finally { close(os); close(bos); } return result; } @SuppressWarnings("unchecked") @Override public M deserialize(byte[] in) { M result = null; ByteArrayInputStream bis = null; ObjectInputStream is = null; try { if (in != null) { bis = new ByteArrayInputStream(in); is = new ObjectInputStream(bis); result = (M) is.readObject(); is.close(); bis.close(); } } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } finally { close(is); close(bis); } return result; } }
接着在新建一個ListTranscoder.java文件,用來序列化存儲List(集合)對象,基本同上,代碼如下:
package cn.com.taiji.sample.utils; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.List; public class ListTranscoder<M extends Serializable> extends SerializeTranscoder { @SuppressWarnings("unchecked") public List<M> deserialize(byte[] in) throws IOException { List<M> list = new ArrayList<>(); ByteArrayInputStream bis = null; ObjectInputStream is = null; try { if (in != null) { bis = new ByteArrayInputStream(in); is = new ObjectInputStream(bis); while (true) { M m = (M)is.readObject(); if (m == null) { break; } list.add(m); } is.close(); bis.close(); } } catch (Exception e) { // e.printStackTrace(); } finally { is.close(); bis.close(); } return list; } @SuppressWarnings("unchecked") @Override public byte[] serialize(Object value) { if (value == null) throw new NullPointerException("Can't serialize null"); List<M> values = (List<M>) value; byte[] results = null; ByteArrayOutputStream bos = null; ObjectOutputStream os = null; try { bos = new ByteArrayOutputStream(); os = new ObjectOutputStream(bos); for (M m : values) { os.writeObject(m); } results = bos.toByteArray(); os.close(); bos.close(); } catch (IOException e) { throw new IllegalArgumentException("Non-serializable object", e); } finally { close(os); close(bos); } return results; } }
現在,就可以用序列化的方式存儲對象或集合了:
try { Jedis jedis = new Jedis(); List<SystemNotice> noticeList = systemNoticeManager.listQuery(noticeQModel); if(noticeList.size()>0 && noticeList != null){ ListTranscoder<SystemNotice> listTranscoder = new ListTranscoder<SystemNotice>(); jedis.set(loginUser.getId().getBytes(), listTranscoder.serialize(noticeList)); } } catch (Exception e) { //如果緩存連不上,則不處理 System.out.println("登錄無法更新該用戶緩存"); }
存的key使用用戶id,所以取出list就很簡單了:
try { Jedis jedis = new Jedis(); byte[] list = jedis.get(loginUser.getId().getBytes()); ListTranscoder<SystemNotice> listTranscoder = new ListTranscoder<SystemNotice>(); List<SystemNotice> newList = listTranscoder.deserialize(list);try { responseJson(JsonTools.toJsonStr(newList), response); } catch (IOException e) { e.printStackTrace(); }
}