所谓集群,就是把多台服务器集合起来,对外提供一个接口访问,对用户来讲彻底透明,经常使用的办法就是前端放一个服务器,将用户请求分发到不一样的服务器,大体有如下几种方案
1)采起DNS轮询:将用户的链接解析到不一样的服务器上,这会产生一个问题,若是一个服务器宕掉,DNS没法及时更新,就会出现问题
2)反向代理服务器:将用户的链接转发到不一样的服务器上,这有两种方式,一个是修改HTTP头,让用户的链接转到固定的服务器,之后再也不和代理服务器交互,这会修改用户浏览器里的地址,可能会不怎么友好;若是不修改地址,用户老是经过代理服务器转接,这个代理服务器可能会成为瓶颈。
3)MAC地址转发,全部的服务器IP地址相同,经过设备指向不一样的机器。
对于代理问题,会产生Session共享的问题,有一种办法就是针对特定用户固定在一台服务器上,这样就不存在Session共享的问题了,这种方法最简单,可是其算法效率比较重要,须要本身选择。还有就是将全部服务器的Session共享,好比放在数据库里、共享目录里或者MemCached里等,可是这些实现方式都有必定的问题,好比保存的数据须要序列化、共享服务器会成为系统薄弱点;再有就是将Session复制,让全部的服务器保持相同的Session信息,这种状况若是须要服务器过多,会严重的影响性能。
系统配置
CentOS 7,192.168.1.14,Apache 80, Nginx 808, Tomcat8 8081, Tomcat8 8082
可选的方案
1)Nginx:固定服务器访问,这个很是简单,修改nginx.conf,采用ip_hash指令,以下
http {
.............
upstream tomcat_server_pool{
ip_hash;
server 192.168.1.14:8081 weight=4 max_fails=2 fail_timeout=30s;
server 192.168.1.14:8082 weight=4 max_fails=2 fail_timeout=30s;
}
server {
listen 808;
server_name localhost;html
charset utf-8;前端
#access_log logs/host.access.log main;java
if (-d $request_filename)
{
rewrite ^/(.*)([^/]) http://$host/$1$2/ permanent;
}
location / {
#root html;
index index.html index.htm index.do;nginx
proxy_next_upstream http_502 http_504 error timeout invalid_header ;
proxy_pass http://tomcat_server_pool;
#proxy_set_header Host www.shiyq.com;
proxy_set_header X-Forwarded-For $remote_addr;
}
能够看出nginx将808端口转发到本机的8081/8082,建立一个spring mvc项目,虚拟目录为study,修改默认的文件,以下
HomeController.java,增长如下内容
@RequestMapping(value = "/index.do", method = RequestMethod.GET)
public String home_do(Locale locale, Model model,HttpServletRequest request) {
logger.info("Welcome home! The client locale is {}.", locale);
Date date = new Date();
DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG);
String formattedDate = dateFormat.format(date);
String host_str = ", the host is " + request.getLocalAddr() + ":" + request.getLocalPort();
HttpSession session = request.getSession();
String check = request.getParameter("check");
if(check != null && !check.equals("")){
session.setAttribute("name", "石永强");
}
logger.info("the name in session is {}", (String)session.getAttribute("name"));
String test_Str = (String) session.getAttribute("host_str");
model.addAttribute("serverTime", formattedDate + ", the host is "+ host_str);
model.addAttribute("name",session.getAttribute("name"));
model.addAttribute("sessionId",session.getId());
return "home";
}
修改home.jsp,内容以下
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>
<html>
<head>
<title>Home</title>
</head>
<body>
<h1>
Hello world!
</h1>web
<P> The time on the server is ${serverTime}. </P>
<P> The name in session is ${name}. </P>
<P> The session id is ${sessionId}. </P>
</body>
</html>
有时候会出现乱码的问题,修改以下内容
在web.xml中加上以下
<filter>
<filter-name>Encoding</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>Encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>算法
上述配置适合解决method=post的问题,若是须要get方式支持中文,如form用get方式提交,或者点击连接支持中文,则须要修改 Tomcat根目录的 conf/server.xml文件中,找<Connector port="8080" />,在里面加<Connector port="8080" uRIEncoding="utf-8" />
注意若是用于开发服务器,须要找到正确的位置,如Eclipse的Servers下的配置文件。
可是在地址栏输入中文,仍然没法支持,只能禁止这种方式。
在这种状况下,访问http://192.168.1.14:808/study/index.do?check=1
输出为
Hello world!
The time on the server is 2014年8月6日 上午11时39分48秒, the host is , the host is 192.168.1.14:8081. spring
The name in session is 石永强. 数据库
The session id is C318A769671490E6822C04752499380F.
刷新以后,能够看到访问的是固定的服务器,这样就能保证用户Session不会出问题
2)使用MemCache
这须要Nginx的session插件,还须要tomcat的memcache插件,但是code.google.com访问不了,虽然文档不少,也实现不了,看之后吧。
只能采用Session复制的方式
3)tomcat 8配置cluster很是简单,固然,这种集群方式采起广播的方式复制Session,当数量到了必定程度必然会引发广播风暴,不适合大型系统
最简单的设置方法:
A)将server.xml中<Cluster>标签注释去掉,默认以下
<Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/>
B)在须要复制Session的web-app中的web.xml增长一行:<distributable/>
C)关掉防火墙:service iptables stop,若是使用的是firewalld,使用命令service firewalld stop
设置Cluster须要注意的地方(官方文档)
a)全部的session属性必须实现java.io.Serializable
b)去掉server.xml中Cluster元素的注释
c)若是要定制valves,确保要设置ReplicationValve
d)确保在web.xml中增长<distributable/>
e)若是使用了mod_jk,在Engine中要设置jvmRoute属性为 workers.properties的worker名称一致
f)确保全部的时间都相同,通过NTP服务器的同步
g)确保你的负载均衡设置为会话粘连模式(sticky session mode)
在浏览器中访问http://192.168.1.104:808/study/index.do,会发如今设置了ip_hash的状况下,根据页面提示,会发现老是访问一个服务器,将这个tomcat关掉,再刷新页面,就会发现自动访问另外一个tomcat,而session信息不变。
并且,若是去掉了ip_hash模式,nginx会自动按顺序依次访问系统,但其session ID不变。
若是要更好的测试能够,能够分别访问http://192.168.1.14:8081/study/index.do和http://192.168.1.14:8082/study/index.do,会发现是一致的session ID,并且还能够访问http://192.168.1.14:8081/study/index.do?check=1,这时候已经设置了session的属性值,而后访问http://192.168.1.14:8082/study/index.do,就能够知道确实发生了Session复制。
若是须要更复杂的定制效果,能够看一下文档
对于防火墙的问题,能够增长以下规则
iptables -A INPUT -i eth0 -d 224.0.0.4 -j ACCEPT
vim /etc/sysconfig/iptables
增长如下内容:
-A INPUT -p udp -m state --state NEW -m udp --dport 45564 -j ACCEPT
启动防火墙
service iptables save
service iptables start
3)Apache+mod_jk+tomcat方案
a)下载apache开发包
yum install httpd-*
b)下载mod_jk
wget http://mirrors.cnnic.cn/apache/tomcat/tomcat-connectors/jk/tomcat-connectors-1.2.40-src.tar.gz
tar xvf tomcat-connectors-1.2.40-src.tar.gz
cd tomcat-connectors-1.2.40-src.tar.gz
cd native
./configure --with-apxs=/bin/apxs
make
make install
c)配置Apache
由于httpd.conf包含conf.module.d目录下文件,在此目录下新建00-add.conf,输入如下内容
LoadModule jk_module modules/mod_jk.so #加载模块
JkWorkersFile conf/worker.properties #加载mod_jk配置文件apache
JkMount /* worker3 #将根目录转发到worker3,worker3是一个负载均衡服务器,包含两台apache服务器vim
<IfModule dir_module>
DirectoryIndex index.jsp index.do
</IfModule>
d)在conf目录下创建workder.properties文件,内容以下
worker.list = worker3
worker.worker1.type=ajp13
worker.worker1.host=localhost
worker.worker1.port=8009
worker.worker1.lbfactor=1
worker.worker1.connection_pool_timeout=600
worker.worker1.socket_keepalive=1
worker.worker1.socket_timeout=60
worker.worker2.type=ajp13
worker.worker2.host=localhost
worker.worker2.port=8010
worker.worker2.lbfactor=1
worker.worker2.connection_pool_timeout=600
worker.worker2.socket_keepalive=1
worker.worker2.socket_timeout=60
worker.worker3.type = lb
worker.worker3.balance_workers = worker1, worker2
能够看出worker1对应本机的8009端口,即前面配置过的tomcat8-1,worker2对应本机的8010端口,即以前配置过的tomcat8-2服务器,worker3表明负载均衡服务器,包括两个成员worker1,worker2
e)配置tomcat
vim /work/tomcat8-1/conf/server.xml
修改以下内容,在Engine标签增长jvmRoute="worker1"
<Engine name="Catalina" defaultHost="localhost" jvmRoute="worker1">
vim /work/tomcat8-2/conf/server.xml
修改以下内容,在Engine标签增长jvmRoute="worker2"
<Engine name="Catalina" defaultHost="localhost" jvmRoute="worker2">
f)重启Apache和tomcat,浏览器中输入http://192.168.1.14/study/index.do,能够看到相似的内容
The time on the server is 2014年8月6日 下午05时21分04秒, the host is , the host is 192.168.1.14:80.
The name in session is .
The session id is AE132D73152E74C043ED64ED6F27707E.worker2. 这里有一个有意思的事情,session id会增长一个i额后缀,即worker1或者workder2,应该是jvmRoute的做用,但本质来讲仍是一个session 用mod_jk的一个问题是不知道访问的是哪台机器,由于显示的apache的地址端口,经过session能够知道究竟是哪台机器。 以前咱们配置过nginx的均衡,浏览器输入http://192.168.1.14:808/study/index.do 会看到session id去掉后缀确实是同样的,并且运行http://192.168.1.14:808/study/index.do?check=1能够看到session信息是共享的。 整体来讲,用nginx配置负载均衡要容易的多,mod_jk要麻烦一些,tomcat的session复制也很是容易,只不过要记住配置防火墙,若是出现问题,要第一时间关掉防火墙,有可能就行了。