Skip to content

Commit b2b5924

Browse files
committed
Add sessionPersistPolicies manager setting to encapsulate numerous options.
1 parent e7bd22a commit b2b5924

File tree

4 files changed

+60
-15
lines changed

4 files changed

+60
-15
lines changed

README.markdown

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,7 @@ Add the following into your Tomcat context.xml (or the context block of the serv
5959
port="6379" <!-- optional: defaults to "6379" -->
6060
database="0" <!-- optional: defaults to "0" -->
6161
maxInactiveInterval="60" <!-- optional: defaults to "60" (in seconds) -->
62+
sessionPersistPolicies="PERSIST_POLICY_1,PERSIST_POLICY_2,.." <!-- optional -->
6263
sentinelMaster="SentinelMasterName" <!-- optional -->
6364
sentinels="sentinel-host-1:port,sentinel-host-2:port,.." <!-- optional --> />
6465

@@ -114,6 +115,14 @@ Then the example above would look like this:
114115
myArray.add(additionalArrayValue);
115116
session.setAttribute("customDirtyFlag");
116117

118+
Persistence Policies
119+
--------------------
120+
121+
With an persistent session storage there is going to be the distinct possibility of race conditions when requests for the same session overlap/occur concurrently. Additionally, because the session manager works by serializing the entire session object into Redis, concurrent updating of the session will exhibit last-write-wins behavior for the entire session (not just specific session attributes).
122+
123+
Since each situation is different, the manager gives you several options which control the details of when/how sessions are persisted. Each of the following options may be selected by setting the `sessionPersistPolicies="PERSIST_POLICY_1,PERSIST_POLICY_2,.."` attributes in your manager declaration in Tomcat's context.xml. Unless noted otherwise, the various options are all combinable.
124+
125+
- `SAVE_ON_CHANGE`: every time `session.setAttribute()` or `session.removeAttribute()` is called the session will be saved. __Note:__ This feature cannot detect changes made to objects already stored in a specific session attribute. __Tradeoffs__: This option will degrade performance slightly as any change to the session will save the session synchronously to Redis.
117126

118127
Possible Issues
119128
---------------
@@ -126,7 +135,7 @@ Normally this should be incredibly unlikely (insert joke about programmers and "
126135

127136
Possible solutions:
128137

129-
- Enable the "save on change" feature by setting `saveOnChange` to `true` in your manager declaration in Tomcat's context.xml. Using this feature will degrade performance slightly as any change to the session will save the session synchronously to Redis, and technically this will still exhibit slight race condition behavior, but it eliminates as much possiblity of errors occurring as possible. __Note__: There's a tradeoff here in that if you make several changes to the session attributes over the lifetime of a long-running request while other short requests are making changes, you'll still end up having the long-running request overwrite the changes made by the short requests. Unfortunately there's no way to completely eliminate all possible race conditions here, so you'll have to determine what's necessary for your specific use case.
138+
- Enable the "save on change" feature (see the Persistence Policies documentation). Technically this will still exhibit slight race condition behavior, but it eliminates as much possiblity of errors occurring as possible. __Note__: There's a tradeoff here in that if you make several changes to the session attributes over the lifetime of a long-running request while other short requests are making changes, you'll still end up having the long-running request overwrite the changes made by the short requests. Unfortunately there's no way to completely eliminate all possible race conditions here, so you'll have to determine what's necessary for your specific use case.
130139
- If you encounter errors, then you can force save the session early (before sending a response to the client) then you can retrieve the current session, and call `currentSession.manager.save(currentSession, true)` to synchronously eliminate the race condition. Note: this will only work directly if your application has the actual session object directly exposed. Many frameworks (and often even Tomcat) will expose the session in their own wrapper HttpSession implementing class. You may be able to dig through these layers to expose the actual underlying RedisSession instance--if so, then using that instance will allow you to implement the workaround.
131140

132141
Acknowledgements

example-app/src/main/java/com/orangefunction/tomcatredissessionmanager/exampleapp/WebApp.java

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -225,8 +225,8 @@ public Object handle(Request request, Response response) {
225225

226226
RedisSessionManager manager = getRedisSessionManager(request);
227227
if (null != manager) {
228-
if (key.equals("saveOnChange")) {
229-
map.put("value", new Boolean(manager.getSaveOnChange()));
228+
if (key.equals("sessionPersistPolicies")) {
229+
map.put("value", manager.getSessionPersistPolicies());
230230
} else if (key.equals("maxInactiveInterval")) {
231231
map.put("value", new Integer(manager.getMaxInactiveInterval()));
232232
}
@@ -248,9 +248,9 @@ public Object handle(Request request, Response response) {
248248

249249
RedisSessionManager manager = getRedisSessionManager(request);
250250
if (null != manager) {
251-
if (key.equals("saveOnChange")) {
252-
manager.setSaveOnChange(Boolean.parseBoolean(value));
253-
map.put("value", new Boolean(manager.getSaveOnChange()));
251+
if (key.equals("sessionPersistPolicies")) {
252+
manager.setSessionPersistPolicies(value);
253+
map.put("value", manager.getSessionPersistPolicies());
254254
} else if (key.equals("maxInactiveInterval")) {
255255
manager.setMaxInactiveInterval(Integer.parseInt(value));
256256
map.put("value", new Integer(manager.getMaxInactiveInterval()));

spec/requests/sessions_spec.rb

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -102,13 +102,15 @@
102102
describe "change on save" do
103103

104104
before :each do
105-
get("#{SETTINGS_PATH}/saveOnChange")
106-
@oldSaveOnChangeValue = json['value']
107-
post("#{SETTINGS_PATH}/saveOnChange", body: {value: 'true'})
105+
get("#{SETTINGS_PATH}/sessionPersistPolicies")
106+
@oldSessionPersistPoliciesValue = json['value']
107+
enums = @oldSessionPersistPoliciesValue.split(',')
108+
enums << 'SAVE_ON_CHANGE'
109+
post("#{SETTINGS_PATH}/sessionPersistPolicies", body: {value: enums.join(',')})
108110
end
109111

110112
after :each do
111-
post("#{SETTINGS_PATH}/saveOnChange", body: {value: @oldSaveOnChangeValue})
113+
post("#{SETTINGS_PATH}/sessionPersistPolicies", body: {value: @oldSessionPersistPoliciesValue})
112114
end
113115

114116
it 'should support persisting the session on change to minimize race conditions on simultaneous updates' do

src/main/java/com/radiadesign/catalina/session/RedisSessionManager.java

Lines changed: 39 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -25,14 +25,30 @@
2525
import java.util.Collections;
2626
import java.util.Enumeration;
2727
import java.util.Set;
28+
import java.util.EnumSet;
2829
import java.util.HashSet;
30+
import java.util.Iterator;
2931

3032
import org.apache.juli.logging.Log;
3133
import org.apache.juli.logging.LogFactory;
3234

3335

3436
public class RedisSessionManager extends ManagerBase implements Lifecycle {
3537

38+
enum SessionPersistPolicy {
39+
DEFAULT,
40+
SAVE_ON_CHANGE;
41+
42+
static SessionPersistPolicy fromName(String name) {
43+
for (SessionPersistPolicy policy : SessionPersistPolicy.values()) {
44+
if (policy.name().equalsIgnoreCase(name)) {
45+
return policy;
46+
}
47+
}
48+
throw new IllegalArgumentException("Invalid session persist policy [" + name + "]. Must be one of " + Arrays.asList(SessionPersistPolicy.values())+ ".");
49+
}
50+
}
51+
3652
protected byte[] NULL_SESSION = "null".getBytes();
3753

3854
private final Log log = LogFactory.getLog(RedisSessionManager.class);
@@ -59,7 +75,7 @@ public class RedisSessionManager extends ManagerBase implements Lifecycle {
5975

6076
protected String serializationStrategyClass = "com.radiadesign.catalina.session.JavaSerializer";
6177

62-
protected boolean saveOnChange = false;
78+
protected EnumSet<SessionPersistPolicy> sessionPersistPoliciesSet = EnumSet.of(SessionPersistPolicy.DEFAULT);
6379

6480
/**
6581
* The lifecycle event support for this component.
@@ -110,12 +126,30 @@ public void setSerializationStrategyClass(String strategy) {
110126
this.serializationStrategyClass = strategy;
111127
}
112128

113-
public boolean getSaveOnChange() {
114-
return saveOnChange;
129+
public String getSessionPersistPolicies() {
130+
StringBuilder policies = new StringBuilder();
131+
for (Iterator<SessionPersistPolicy> iter = this.sessionPersistPoliciesSet.iterator(); iter.hasNext();) {
132+
SessionPersistPolicy policy = iter.next();
133+
policies.append(policy.name());
134+
if (iter.hasNext()) {
135+
policies.append(",");
136+
}
137+
}
138+
return policies.toString();
139+
}
140+
141+
public void setSessionPersistPolicies(String sessionPersistPolicies) {
142+
String[] policyArray = sessionPersistPolicies.split(",");
143+
EnumSet<SessionPersistPolicy> policySet = EnumSet.of(SessionPersistPolicy.DEFAULT);
144+
for (String policyName : policyArray) {
145+
SessionPersistPolicy policy = SessionPersistPolicy.fromName(policyName);
146+
policySet.add(policy);
147+
}
148+
this.sessionPersistPoliciesSet = policySet;
115149
}
116150

117-
public void setSaveOnChange(boolean saveOnChange) {
118-
this.saveOnChange = saveOnChange;
151+
public boolean getSaveOnChange() {
152+
return this.sessionPersistPoliciesSet.contains(SessionPersistPolicy.SAVE_ON_CHANGE);
119153
}
120154

121155
public String getSentinels() {

0 commit comments

Comments
 (0)