1)确保正确的安装了apache httpd服务器
2)确保安装了mod_jk模块,在类unix的路径为apache/modules/mod_jk.so
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
# 加载mod_jk模块 LoadModule jk_module modules/mod_jk.so # 指定 workers.properties位置 JkWorkersFile /usr/local/apache2/conf/workers.properties # jk shared memory位置 JkShmFile /var/log/httpd/mod_jk.shm # jk logs JkLogFile /var/log/httpd/mod_jk.log # Set the jk log level [debug/error/info] JkLogLevel debug # log时间戳格式 JkLogStampFormat "[%a %b %d %H:%M:%S %Y] " JkMount /testoom/* LB_worker JkMount /admin/status jkstatus |
# 将请求路由给对应的worker,可用的worker为worker.properties文件的worker.list属性中指定的worker
#本例将所有"/testoom/*"请求路由给LB_worker 处理,将"/admin/status"请求路由给jkstatus处理
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
worker.list=LB_worker,jkstatus worker.worker1.type=ajp13 worker.worker1.host=10.52.26.24 worker.worker1.port=8009 worker.worker1.lbfactor=1 worker.worker2.host=10.52.26.24 worker.worker2.port=9009 worker.worker2.type=ajp13 worker.worker2.lbfactor=1 worker.LB_worker.type=lb worker.LB_worker.retries=3 worker.LB_worker.balance_workers=worker1,worker2 worker.LB_worker.sticky_session=true worker.LB_worker.sticky_session_force=true worker.jkstatus.type=status |
worker.type可取的值为(ajp13[tomcat路由worker], lb[负载worker], status[status worker]),
上 面的代码配置了一个load balance worker和一个status worker,外加两个工作worker(worker1, worker2),load balance worker收到请求后根据均衡策略和负载因子(lbfactor)将对应的请求路由给worker1和worker2。
server.xml的Engine定义时需要将jvmRoute属性指定为对应的worker的名称。
<Engine name="Catalina" defaultHost="localhost" jvmRoute="worker1">
测试1
通过-D选项给每个tomcat 示例赋予一个唯一值,可以在catalina.bat中添加如下行实现:
set "JAVA_OPTS=-Dxx9527=worker1"
我们定义的系统属性的值为work1
然后写一个servlet:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
public class TestServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String username = (String)req.getSession().getAttribute("username"); Integer count = (Integer)req.getSession().getAttribute("count"); if(username == null) { username = req.getParameter("username"); if(username == null) { resp.getWriter().write("please provide username"); return ; } count = Integer.valueOf(0); req.getSession().setAttribute("username", username); } count = count + 1; req.getSession().setAttribute("count", count); String domain = System.getProperty("xx9527"); resp.getWriter().write( String.format("[from %s], hi %s, you have requested %d times ", domain, username, count.intValue())); } } |
这 段代码很简单,先获取session中是否有username和count属性,如果没有,就从当前的请求中获取username属性,如果还是没有就提 示错误返回,如果当前的请求中有username属性将count初始化为0,将username属性放入session中。将count+1,表示在该 session中用户的请求数加1,调用System.getProperty("xx9527")获取系统属性值,最后将拼接的信息返回给用户,格式 为:
[from worker2], hi javacoder.cn, you have requested? 5 times
测试2
调用localhost/admin/status 获取load balance的状态信息
Posted in: 服务器 | Tags: load balance, tomcat, 负载均衡
Comments are closed.