Mac下Nginx负载+Tomcat集群+memcached实现session共享

最近,要接手cas的单点认证,所以提前学习了这个。nginx负载、分发多台tomcat的过程中,memcached实现了session共享。虽然网上也有很多的示例,总结下自己吸收到的并记录下来。

nginx简单安装配置:

  • 首先安装下nginx,我这安装的是1.15.1
pengchengdeMacBook-Pro:nginx pengcheng$ nginx -v
nginx version: nginx/1.15.1
  • 查看完版本,可以试试启动和停下nginx服务器。
  1. 启动命令:sudo nginx(nginx默认端口是80,直接访问http://localhost,会有个欢迎页面)
  2. 停止命令:sudo nginx -s stop
  3. 重启命令:sudo nginx -s reload
  4. 杀进程停止有三种方式:从容停止、快速停止和强制停止。我这使用的话,就是 快速停止:
pengchengdeMacBook-Pro:nginx pengcheng$ ps -ef | grep nginx
    0  7183     1   0  2:22下午 ??         0:00.00 nginx: master process nginx
   -2  7184  7183   0  2:22下午 ??         0:00.00 nginx: worker process
  501  7298   899   0  2:27下午 ttys000    0:00.00 grep nginx
pengchengdeMacBook-Pro:nginx pengcheng$ sudo kill -TERM 7183
  • 了解下nginx特性
  1. 负载均衡
  2. 动静分离
  3. 反向代理
  • 使用brew安装的nginx默认安装在
pengchengdeMacBook-Pro:nginx pengcheng$ pwd
/usr/local/etc/nginx

  • 在上述文件夹下面,修改配置文件nginx.conf,负载需要在http里面的server上面添加upstream,test_cluster是随意自定义的。其中有几台机器就配置几个server,weight对应的数字越大,负载的几率越大。同时server的location中要添加proxy_pass对应刚才随意自定义的名。至此,nginx这边的简单配置,就先这样。
upstream test_cluster {
    server localhost:8081 weight=1;
    server localhost:9080 weight=2;
}
location / {
     root   html;
     index  index.html index.htm;
     proxy_pass http://test_cluster;
}

tomcat配置:

  • 准备了2个tomcat。tomcat1和tomcat2,本来的端口都是默认8080,修改tomcat1的端口为8081,修改tomcat2的端口9080(server.xml中)。在上面,在nginx中配置了这两台server。
  • 测试负载,先分别启动这两个tomcat,再启动nginx。直接访问http://localhost,可以随机负载tomcat1和tomcat2,表示负载安装成功,反正失败。

memcached集成tomcat中:

pengchengdeMacBook-Pro:/ pengcheng$ memcached -d -p 11211 -u nobody -c 1024 -m 64
pengchengdeMacBook-Pro:/ pengcheng$ telnet localhost 11211
Trying ::1...
Connected to localhost.
Escape character is '^]'.

  • 退出:quit
  • 在两个tomcat的context.xml中,context标签下添加memcached配置信息,下面的是采用了效率最高的kryo序列化tomcat配置方式,还有其他四种序列方式:java默认序列化、javolution序列化、xstream序列化和flexjson序列化(有兴趣可以查查)。
<Manager className="de.javakaffee.web.msm.MemcachedBackupSessionManager" 
    memcachedNodes="n1:127.0.0.1:11211" 
    sticky="false" 
    requestUriIgnorePattern= ".*\.(png|gif|jpg|css|js)$"   
    sessionBackupAsync= "true"  
    sessionBackupTimeout= "1800000"     
    copyCollectionsForSerialization="false"
    transcoderFactoryClass="de.javakaffee.web.msm.serializer.kryo.KryoTranscoderFactory"   
  />

对应序列化,要往tomcat的lib下添加对应的jar包。

《Mac下Nginx负载+Tomcat集群+memcached实现session共享》 可以自己找或者滴滴我

    原文作者:Hush____
    原文地址: https://www.jianshu.com/p/e6b98912c9e8
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞