Servlet3.0筆記之Redis操作示范Retwis Java版
Retwis-JAVA,基于Servlet 3.0 + UrlRewrite + Freemarker + Jedis。示范運行在Tomcat 7中,redis為***的2.22版本,jedis為redis的java客戶端操作框架。在Servlet 3.0規(guī)范中,對Url映射處理依然沒有進步,因此只能使用UrlRewrite框架讓部分url看起來友好一些。另外,項目沒有使用IOC容器框架,沒有使用MVC框架,代碼量稍微多些,代碼相對耦合一些。若使用Struts2 + Spring 代碼量會少一些。
對涉及到的redis存儲結(jié)構(gòu),大致如下:

涉及到的兩個對象很簡單:

序列化后以二進制數(shù)據(jù)保存到redis中:
- private byte [] object2Bytes(V value) {
- if (value == null )
- return null ;
- ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
- ObjectOutputStream outputStream;
- try {
- outputStream = new ObjectOutputStream(arrayOutputStream);
- outputStream.writeObject(value);
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- try {
- arrayOutputStream.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- return arrayOutputStream.toByteArray();
- }
- public void save(String key, V value) {
- jedis.set(getKey(key), object2Bytes(value));
- }
獲取用戶的timeline時,redis的LRANGE命令提供對list類型數(shù)據(jù)提供分頁操作:
- private List < Status > timeline(String targetId, int page) {
- if (page < 1 )
- page = 1 ;
- int startIndex = (page - 1 ) * 10 ;
- int endIndex = page * 10 ;
- List < String > idList = super .jedis
- .lrange(targetId, startIndex, endIndex);
- if (idList.isEmpty())
- return new ArrayList < Status > ( 0 );
- List < Status > statusList = new ArrayList < Status > (idList.size());
- for (String id : idList) {
- Status status = load(Long.valueOf(id));
- if (status == null )
- continue ;
- status.setUser(userService.load(status.getUid()));
- statusList.add(status);
- }
- return statusList;
- }
很顯然,LRANGE取出了Status對象的ID,然后我們需要再次根據(jù)ID獲取對應(yīng)的Status對象二進制數(shù)據(jù),然后反序列化:
- public Status load( long id) {
- return super .get(getFormatId(id));
- }
- private String getFormatId( long id) {
- return String.format(STATUS_ID_FORMAT, id);
- }
- private static final String STATUS_ID_FORMAT = " status:id:%d " ;
- public V get(String key) {
- return byte2Object(jedis.get(getKey(key)));
- }
- @SuppressWarnings( " unchecked " )
- private V byte2Object( byte [] bytes) {
- if (bytes == null || bytes.length == 0 )
- return null ;
- try {
- ObjectInputStream inputStream;
- inputStream = new ObjectInputStream( new ByteArrayInputStream(bytes));
- Object obj = inputStream.readObject();
- return (V) obj;
- } catch (IOException e) {
- e.printStackTrace();
- } catch (ClassNotFoundException e) {
- e.printStackTrace();
- }
- return null ;
- }
以上使用JDK內(nèi)置的序列化支持;更多序列化,可參考hessian、google protobuf等序列化框架,后者提供業(yè)界更為成熟的跨平臺、更為高效的序列化方案。更多代碼請參見附件。
一些總結(jié)和思考:
不僅僅是緩存,替代SQL數(shù)據(jù)庫已完全成為可能,更高效,更經(jīng)濟;雖然只是打開了一扇小的窗戶,但說不準(zhǔn)以后人們會把大門打開。
實際環(huán)境中,可能***方式為SQL + NOSQL配合使用,互相彌補不足;還好,redis指令不算多,可速查,簡單易記。
JAVA和RUBY代碼相比,有些重
另:
在線版,請參考 http://retwisrb.danlucraft.com/。那個誰誰,要運行范例,保證redis運行才行。
【編輯推薦】