問題:當業務使用了SSESSION保存某些對象,怎樣在集羣時複製這些對象?
TOMCAT5已經考慮過這種集羣所導致的問題,其實也就是cluster的問題。
如果採用了TOMCAT 的cluster解決方案,我相信應該可以保證session等信息的同步可操作。
另外,TOMCAT要求放到SESSION裏的對象要需要實現Serializable,以確保各個對象能被正常複製。
有人提出疑問,SESSION使用的是MAP來保存數據,序列化時不會把實際的對象序列化。其實看看HashMap序列化的代碼就可以知道,在SESSION序列化時,是可以正確將Map中保存的數據對象序列化的。更主要的是,TOMCAT序列化SESSION時,並沒有使用HashMap的序列化方式,而是將各個保存的對象讀出來單獨進行序列化。
因此保存到SESSION中的對象實例應該也會被複制。
這樣就可以保證各個服務器上的內存數據一樣了。
另外一個問題是許多人擔心 TOMCAT 的這個解決發方案的性能問題,其實同步某某些內容信息如SESSION的代價並不是很大的,特別在幾臺工作站屬於同一個網內。想對其帶來的橫向擴展性能,可以忽略,我想。
參考:
TOMCAT中SESSION序列化的代碼:
protected void writeObject(ObjectOutputStream stream) throws IOException {
// Write the scalar instance variables (except Manager)
stream.writeObject(new Long(creationTime));
stream.writeObject(new Long(lastAccessedTime));
stream.writeObject(new Integer(maxInactiveInterval));
stream.writeObject(new Boolean(isNew));
stream.writeObject(new Boolean(isValid));
stream.writeObject(new Long(thisAccessedTime));
stream.writeObject(id);
if (debug >= 2)
log("writeObject() storing session " + id);
// Accumulate the names of serializable and non-serializable attributes
String keys[] = keys();
ArrayList saveNames = new ArrayList();
ArrayList saveValues = new ArrayList();
for (int i = 0; i < keys.length; i++) {
Object value = null;
synchronized (attributes) {
value = attributes.get(keys[i]);
}
if (value == null)
continue;
else if (value instanceof Serializable) {
saveNames.add(keys[i]);
saveValues.add(value);
}
}
// Serialize the attribute count and the Serializable attributes
int n = saveNames.size();
stream.writeObject(new Integer(n));
for (int i = 0; i < n; i++) {
stream.writeObject((String) saveNames.get(i));
try {
stream.writeObject(saveValues.get(i));
if (debug >= 2)
log(" storing attribute '" + saveNames.get(i) +
"' with value '" + saveValues.get(i) + "'");
} catch (NotSerializableException e) {
log(sm.getString("standardSession.notSerializable",
saveNames.get(i), id), e);
stream.writeObject(NOT_SERIALIZED);
if (debug >= 2)
log(" storing attribute '" + saveNames.get(i) +
"' with value NOT_SERIALIZED");
}
}
}
HashMap序列化的代碼:
private void writeObject(java.io.ObjectOutputStream s)
throws IOException
{
// Write out the threshold, loadfactor, and any hidden stuff
s.defaultWriteObject();
// Write out number of buckets
s.writeInt(table.length);
// Write out size (number of Mappings)
s.writeInt(size);
// Write out keys and values (alternating)
for (Iterator i = entrySet().iterator(); i.hasNext(); ) {
Map.Entry e = (Map.Entry) i.next();
s.writeObject(e.getKey());
s.writeObject(e.getValue());
}
}