Common web architecture is Web – WAS – (DB). For example, Apache as Web Server and Tomcat as WAS. In this case, mod_jk is is used to connect from Apache to Tomcat. The following is Web to WAS load balancing architecture.
With this architecture, multiple http request is sent to Tomcat#1 and Tomcat#2 in round robin. If the server application use servlet session, the following scenario happens.
step 1) A client connects to Tomcat#1. Tomcat#1 creates a session
step 2) the client connects to Tomcat#2 with previous session. But Tomcat#2 does not know the session, therefore previous status at Tomcat#1 can not be continued (when session cluster is not enabled)
To resolve this problem, Tomcat and Apache supports sticky session. With sticky session, mod_jk routes the request to the Tomcat which generated the session. For the previous scenario, step2 goes to Tomcat#1 although mod_jk is working in load balancing.
How to setup sticky session
1) To name each Tomcat instance
Inside server.xml, instance name must be defined.
<Engine name="Catalina" defaultHost="localhost" jvmRoute="test1">
Each instance must have unique name.
2) To enable mod_jk
To enable mod_jk in Apache http server, the following config is needed.
httpd.conf |
---|
… Include conf/mod_jk.conf … |
mod_jk.conf |
---|
LoadModule jk_module modules/mod_jk.so
JkWorkersFile conf/workers.properties
JkLogFile “|/usr/local/httpd-2.2.27/bin/rotatelogs -l /usr/local/httpd-2.2.27/logs/mod_jk_test.log.%Y%m%d 86400”
JkLogLevel info
JkShmFile logs/mod_jk_test.shm
JkMountFile conf/uri.properties
JkWatchdogInterval 60
|
workers.properties |
---|
worker.list=test_worker
worker.test_worker.type=lb
worker.test_worker.balance_workers=test1, test2
worker.test1.host=host_ip
worker.test1.port=8009
worker.test1.type=ajp13
worker.test2.host=host_ip
worker.test2.port=8009
worker.test2.type=ajp13
|
- test_worker, test1 and test2 are worker name.
- test_worker is load balancer. It balances test1 and test2.
- test1 and test2 are ajp worker which point to each Tomcat instance.
- ajp worker name must be same with jvmRoute in Tomcat server.xml
- More options
uri.properties |
---|
/*=test_worker |
- This file defines which worker is used for which url pattern. This example shows that all requests are handled by test_worker (the name must be declared in workers.properties)
How sticky session works
- If jvmRoute attribute is set, Tomcat generates a session id with the following format
session_random_value.jvmRouteValue
(ex. 9E4E7AE669AEFDF68CC03A35E4636646.test1) - This session id is returned to client as a cookie
ex) Cookie : JSESSIONID=9E4E7AE669AEFDF68CC03A35E4636646.test1 - Next time, the client connects with the cookie
- mod_jk parses JSESSIONID and extracts server name (for this example, test1)
- mod_jk sends the request to the same named worker (which is defined at workers.properties)