redis cache server (nginx + tomcat + redis + mysql realize session session sharing)

A, redis Introduction

redis is a key-value storage system. And the like memcached, it supports the type of stored value relatively more, including string (string), list (list), set (collection), zset (sorted set --- ordered collection) and hash (hash type). Like with memcached, in order to ensure efficiency, the data is cached in memory. Redis difference is periodically updated data is written to the disk or to modify the operation of writing additional log file, and implements master-slave (master-slave) synchronized on this basis.

Redis is a key-value high-performance database. redis appears, to a large extent compensate for the lack of memcacehd such key / value store, it can play a very good complement to relational database in some situations. It provides java, C / C ++, C #, php, javaScript, Perl, Object-C, python, Ruby and other clients, very easy to use.
If the differences between simple and redis memcached there are basically the following three points:
. 1, redis only support simple key / value data types, while also providing a storage list, set, zset, hash and other data structures.
2, redis support backup data, i.e., data backup master-slave mode.
3, redis support data persistence, data in memory can be kept on disk, restart when you can load be used again.

In the Reids, not all the data have been stored in memory. This is compared to a memcacehd and the biggest difference.
Redis will cache all the key information, if Reids find memory usage exceeds a certain threshold, it will trigger the swap operation, Redis based on “swappability = age*log(size_in_memory)”the need to swap disks calculated value corresponding to those key. Then the key corresponding to the value persisted to disk, and clear in memory. This feature allows the data may be stored redis exceed its memory size of the machine itself. Of course, the machine itself memory must be able to keep all of eky, because these data are not carried out swap operations.
When reading data from the Redis, if the key corresponding to the read memory value no, then Redis need to load the corresponding data from the swap file, then returned to the requester.

memcached and redis comparison
1, network IO model
memcacehd is multi-threaded, non-blocking network model IO multiplexed into the main thread and the worker monitor child thread, monitor network listener thread connection, after receiving the request, the delivery pipe connection descriptor to the worker thread, read and write IO, network layer package libevent event repository, multi-threaded multi-core model can play a role.
Redis IO multiplexing using a single-threaded model that he encapsulates a simple AeEvent event-handling framework, the main achievement of epoll, kqueue and select, only for simple IO operation, the single-threaded speed advantage can play to the maximum, but Redis also provides some simple calculation functions, such as sorting, polymerization, etc. for these operations, the actual single-threading model will seriously affect the overall throughput, CPU calculation process, the entire IO scheduling are blocked live.

2, memory management
memcacehd using the pre-allocated memory pool manner using different sizes slab and chunk for memory management, value select the appropriate chunk size according to storage.
Redis application memory use on-site way to store data.

3, storage and other aspects
memcached substantially only supports simple key-value store, and do not support persistent replication and other functions, in addition to the Redis key / value, supports list, set, sortedset, hash and other data structures.

Second, how to keep the session session

Currently, in order to be able to adapt to large-scale web access, the need to achieve a clustered deployment applications. The most effective solution is to cluster load balancing and load balancing, each user requests are likely to be assigned to the server is not fixed, so we must first solve the unified session to ensure that regardless of the user's request is forwarded to the server on which We can ensure the normal use of users that need to implement mechanisms for sharing the session.

In the session to achieve uniform cluster system has the following several options:
1, precise positioning request (sessionsticky)
e.g. ip hash-based access policy, i.e., the current user request definitions are concentrated to a server, the server stores a single such the user's login session, if downtime is equivalent to a single point of deployment will be lost, the session is not copied. (Not used)
2, session replication share (sessionreplication):
as tomcat comes session share, mainly refers to the cluster environment, synchronization session between multiple application servers, keeping the session, foreign transparent. If one server fails, depending on the load balancing principle, the scheduler will traverse to find available nodes, distribution request, since the session has been synchronized, it can ensure that the user's session information is not lost, session replication.
The shortcomings of this program:
must be completed between the same kind of middleware (eg: between Tomcat-Tomcat)
session replication performance penalty will quickly increase, especially to save a larger object when the session and objects when the rapid changes in performance degradation is more significant, will consume system performance. This feature allows horizontal expansion of the web application is limited.
content by broadcast synchronization session to the members, will cause network traffic bottlenecks, even within the network bottleneck. In large concurrent performance is not good.
3, based on the cache DB cache sharing session
sharing session based memcache / redis cache, i.e. using cacheDB store session information, the application server to accept new requests session information is stored in the cache DB when the application server fails, the scheduler iterates Looking for available nodes, distribution request, when the application server session is not found in the machine's memory, the cache DB to find, if found then copied to the machine, so to achieve the session sharing and high availability. (Recommended Use)

Three, nginx + tomcat + redis + mysql realize session sharing, load balancing

1, project environment

Host computer operating system ip address
nginx CentOS 7.3 172.16.1.100
tomcat-1 CentOS 7.3 172.16.1.110
tomcat-2 CentOS 7.3 172.16.1.120
mysql CentOS 7.3 172.16.1.130
Redis CentOS 7.3 172.16.1.30

2, the project topology

redis cache server (nginx + tomcat + redis + mysql realize session session sharing)
In this figure, the reverse proxy Nginx done to achieve separation of static and dynamic, dynamic client request to the server randomly assigned to two tomcat according to the weight, as Redis two tomcat share session data server, mysql tomcat of two back-end database.

3, project implementation

1, nginx installation configuration
using nginx as a load balancer tomcat, tomcat session stored in the session data redis, 7x24 effect can be achieved with zero downtime. Because the session is stored in redis, so you do not have to configure nginx said stick paste a tomcat way, so as to realize more background tomcat load balancing.

1)安装依赖工具包:
[root@nginx ~]#  yum -y install gcc* pcre-devel openssl-devel zlib-devel make vim 
2)创建nginx程序用户组和用户:
[root@nginx ~]# groupadd -r nginx && useradd -r -g nginx -s /bin/false -M nginx
3)编译安装nginx:
[root@nginx ~]# tar zxf nginx-1.8.0.tar.gz 
[root@nginx ~]# cd nginx-1.8.0
[root@nginx nginx-1.8.0]# ./configure --prefix=/usr/local/nginx --user=nginx --group=nginx \
>  --with-http_stub_status_module --with-http_ssl_module  --with-http_dav_module  --with-http_flv_module \
>  --with-http_mp4_module --with-http_gzip_static_module --with-http_gzip_static_module \
> --with-http_addition_module --with-http_sub_module  --with-pcre  --with-http_realip_module 
[root@nginx nginx-1.8.0]# make && make install
4)优化路径并检查:
[root@nginx nginx-1.8.0]# ln -s /usr/local/nginx/sbin/nginx /usr/local/sbin/
[root@nginx nginx-1.8.0]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
5)编写nginx服务脚本:
[root@nginx nginx-1.8.0]# vim /etc/init.d/nginx
#!/bin/bash
# chkconfig: 2345 99 20
# description: Nginx Service Control Script
PROG="/usr/local/nginx/sbin/nginx"
PIDF="/usr/local/nginx/logs/nginx.pid"
case "$1" in
start)
netstat -anplt |grep ":80" &> /dev/null && pgrep "nginx" &> /dev/null
if [ $? -eq 0 ]
then
echo "Nginx service already running."
else
$PROG -t &> /dev/null
if [ $? -eq 0 ] ; then
$PROG
echo "Nginx service start success."
else
$PROG -t
fi
fi
;;
stop)
netstat -anplt |grep ":80" &> /dev/null && pgrep "nginx" &> /dev/null
if [ $? -eq 0 ]
then
kill -s QUIT $(cat $PIDF)
echo "Nginx service stop success."
else
echo "Nginx service already stop"
fi
;;
restart)
$0 stop
$0 start
;;
status)
netstat -anplt |grep ":80" &> /dev/null && pgrep "nginx" &> /dev/null
if [ $? -eq 0 ]
then
echo "Nginx service is running."
else
echo "Nginx is stop."
fi
;;
reload)
netstat -anplt |grep ":80" &> /dev/null && pgrep "nginx" &> /dev/null
if [ $? -eq 0 ]
then
$PROG -t &> /dev/null
if [ $? -eq 0 ] ; then
kill -s HUP $(cat $PIDF)
echo "reload Nginx config success."
else
$PROG -t
fi
else
echo "Nginx service is not run."
fi
;;
*)
echo "Usage: $0 {start|stop|restart|reload}"
exit 1
esac
#并加入开机自启:
[root@nginx ~]# chkconfig --add nginx
[root@nginx ~]# chkconfig nginx on
#启动nginx:
[root@nginx ~]# systemctl daemon-reload
[root@nginx ~]# systemctl start nginx
[root@nginx ~]# netstat -anput | grep nginx
tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      21812/nginx: master 

6) arranged nginx reverse proxy (reverse proxy load balancer + + health detection)
Note: binding rear end proxy module for web upstream and load balancing;
binding nginx module and the default comes ngx_http_proxy_module ngx_http_upstream_module backend server module for health check ;

[root@nginx ~]# vim /usr/local/nginx/conf/nginx.conf
Add the following configuration items http {} field:

#load balance Settings:
        upstream  backend_tomcat {   
                server 172.16.1.110:8080 weight=1 max_fails=2 fail_timeout=10s;
                server 172.16.1.120:8080 weight=1 max_fails=2 fail_timeout=10s;
}
# http_proxy Settings:
        proxy_connect_timeout 75;   #nginx 跟后端服务器连接超时时间(代理连接超时)
        proxy_send_timeout 75;   #定义后端服务器的数据回传时间,即在规定时间之内后端服务器必须传完所有的数据,否则,nginx将断开这个连接。
        proxy_read_timeout 75;  #定义从后端服务器读取响应的超时
        proxy_buffer_size 4k;  #设置缓冲区的大小(该缓冲区大小默认等于 proxy_buffers 指令设置的一块缓冲区的大小,但它也可以被设置得更小)
        proxy_buffers 4 32k;    #为每个连接设置缓冲区的数量和每块缓冲区的大小
        proxy_busy_buffers_size 64k;  #高负荷下缓冲大小(默认大小是 proxy_buffers 指令设置单块缓冲大小的 2 倍)
        proxy_temp_file_write_size 64k;  #当缓存被代理的服务器响应到临时文件时,这个选项限制每次写临时文件的大小
参数解释:
weight:轮询权值,也是可以用在ip_hash的,默认值为1
max_fails:运行请求失败的次数,默认为1。当超过最大次数时,返回proxy_next_upstream模块定义的错误。
fail_timeout:有两层含义,以时在10s时间内最多容许2次失败;二是在经历了2次失败以后,10s时间内不分配请求到这台服务器。

In the server module to add:

#proxy_pass Settings:
        location ~* \.(jsp|do)$ {   #匹配到的动态请求将进行转发
        proxy_pass http://backend_tomcat;  #请求转向 backend 定义的服务器列表,即反向代理,对应 upstream 负载均衡器。
        proxy_redirect off;  #是否定义重定向规则
        proxy_set_header Host $host;  #允许重新定义或者添加发往后端服务器的请求头
        proxy_set_header X-Real-IP $remote_addr;   #web服务器端获得用户的真实ip, 也可以通过下面的X-Forward-For获取
        proxy_set_header X-Forwarded-For   $proxy_add_x_forwarded_for;    #后端的 Web 服务器可以通过 X-Forwarded-For 获取用户真实 IP
        proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
#增加故障转移,如果后端的服务器返回502、 504、执行超时等错误,自动将请求转发到upstream负载均衡池中的另一台服务器,实现故障转移
}

7) Restart nginx service and set firewall rules:

[root@nginx ~]# systemctl restart nginx
[root@nginx ~]# firewall-cmd --add-port=80/tcp --permanent
success
[root@nginx ~]# firewall-cmd --reload
success

2, installation and deployment tomcat server
must be installed before installing tomcat JDK, JDK is provided free sun java language software development kit, which includes java virtual machine (JVM), write good java source code can be compiled to form java byte code, as long as the JDK installation, you can use the JVM interprets the bytecode files, thus ensuring the platform of the java.

1) installation JDK, arranged java environment (tomcat1 server installation and tomcat2)

[root@tomcat-1 ~]# tar zxf jdk-8u211-linux-x64.tar.gz
[root@tomcat-1 ~]# mv jdk1.8.0_211/ /usr/local/java
[root@tomcat-1 ~]# vim /etc/profile
export JAVA_HOME=/usr/local/java
export PATH=$JAVA_HOME/bin:$PATH
[root@tomcat-1 ~]# source /etc/profile
[root@tomcat-1 ~]# java -version  #确保java版本与当前版本一致
java version "1.8.0_211"
Java(TM) SE Runtime Environment (build 1.8.0_211-b12)
Java HotSpot(TM) 64-Bit Server VM (build 25.211-b12, mixed mode)

2) Installation tomcat (tomcat1 tomcat2 server and the same operation)
version available tomcat official website to download required: https://tomcat.apache.org

[root@tomcat-1 ~]# tar zxf apache-tomcat-8.5.35.tar.gz 
[root@tomcat-1 ~]# mv apache-tomcat-8.5.35 /usr/local/tomcat8
[root@tomcat-1 ~]# vim /etc/profile
export CATALINA_HOME=/usr/local/tomcat8
export PATH=$JAVA_HOME/bin:$CATALINA_HOME/bin:$PATH
[root@tomcat-1 ~]# source /etc/profile
#启动tomcat:
[root@tomcat-1 ~]# /usr/local/tomcat8/bin/startup.sh   
#这里只是展示启动脚本的路径,因为上边设置了环境变量,可直接执行startup.sh脚本
Using CATALINA_BASE:   /usr/local/tomcat8
Using CATALINA_HOME:   /usr/local/tomcat8
Using CATALINA_TMPDIR: /usr/local/tomcat8/temp
Using JRE_HOME:        /usr/local/java
Using CLASSPATH:       /usr/local/tomcat8/bin/bootstrap.jar:/usr/local/tomcat8/bin/tomcat-juli.jar
Tomcat started.
[root@tomcat-1 ~]# netstat -anput | grep 8080
tcp6       0      0 :::8080                 :::*                    LISTEN      15408/java
#防火墙规则配置:
[root@tomcat-1 ~]# firewall-cmd --add-port=8080/tcp --permanent
success
[root@tomcat-1 ~]# firewall-cmd --reload
success

Two test access tomcat server browser #
redis cache server (nginx + tomcat + redis + mysql realize session session sharing)
redis cache server (nginx + tomcat + redis + mysql realize session session sharing)

3) Modify tomcat profile (tomcat1 and tomcat2 operation)

[root@tomcat-1 ~]# vim /usr/local/tomcat8/conf/server.xml
#设置默认虚拟主机,并增加jvmRoute
<Engine name="Catalina" defaultHost="localhost" jvmRoute="tomcat-1">
#修改默认虚拟主机,并将网站文件路径指向/web/webapp1,在host段增加context段
 <Host name="localhost"  appBase="webapps"
            unpackWARs="true" autoDeploy="true">
                <Context docBase="/web/webapp1" path="" reloadable="true"/>   #添加该行内容

# Tomcat-2 server configuration file:

#两台配置只是jvmRoute不同,其他配置保持一致:
<Engine name="Catalina" defaultHost="localhost" jvmRoute="tomcat-2">
<Host name="localhost"  appBase="webapps"
            unpackWARs="true" autoDeploy="true">
                  <Context docBase="/web/webapp1" path="" reloadable="true"/> 

Description: jvmRoute is jvm logo, the page is the most top of the tab, in the actual production environment, all the background tomcat logo to be the same, here for illustrative experiment, I have two tomcat logo change is not the same. In order to verify a good time and so we will verify.

4) Create a web directory and test file: (tomcat-1 and the same operation tomcat-2)

[root@tomcat-1 ~]# mkdir -p /web/webapp1
[root@tomcat-1 ~]# vim /web/webapp1/index.jsp  #编写动态网页文件
#内容如下:
<%@page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<html>
<head>
<title>tomcat-1</title>   
</head>
<body>
<h1><font color="red">Session serviced by tomcat</font></h1>
<table aligh="center" border="1">
<tr>
<td>Session ID</td>
<td><%=session.getId() %></td>
<% session.setAttribute("abc","abc");%>
</tr>
<tr>
<td>Created on</td>
<td><%= session.getCreationTime() %></td>
</tr>
</table>
</body>
<html>

# Note: To test load balancing, tomcat-2 node index.jsp file title changed to "tomcat-2" (web content production environment tomcat server provides two are the same), the same as other configurations.

5) Restart tomct service, and verify load balancing

#tomcat-1和tomcat-2都需要重启
[root@tomcat-1 ~]# shutdown.sh 
[root@tomcat-1 ~]# startup.sh   
[root@tomcat-1 ~]# netstat -anput | grep 8080
tcp6       0      0 :::8080                 :::*                    LISTEN      15551/java  

# Users to use a browser by accessing the nginx web service, verify load balancing:
the first visit of results:
redis cache server (nginx + tomcat + redis + mysql realize session session sharing)
the results of the second visit of:
redis cache server (nginx + tomcat + redis + mysql realize session session sharing)
From the above results can be seen in two visits, nginx to access requests are distributed to the rear end tomcat-1 and tomcat-2, client access request to achieve load balancing, but not the same session id (ie: does not implement session remain), so, back-end server will cause a lot of pressure.

6) Verify health check

#可以关掉一台tomcat主机,模拟宕机,用客户端浏览器测试访问
[root@tomcat-1 ~]# shutdown.sh   
Using CATALINA_BASE:   /usr/local/tomcat8
Using CATALINA_HOME:   /usr/local/tomcat8
Using CATALINA_TMPDIR: /usr/local/tomcat8/temp
Using JRE_HOME:        /usr/local/java
Using CLASSPATH:       /usr/local/tomcat8/bin/bootstrap.jar:/usr/local/tomcat8/bin/tomcat-juli.jar

redis cache server (nginx + tomcat + redis + mysql realize session session sharing)
No matter how you refresh the page, has been tomcat2 provide services, health checks explanation played a role, the validation is successful.

3, the session remains tomcat configuration is achieved by redis

# Front can be said that the preparatory work, the following is the focus of the project.
1) mounted redis
official website Download: http://download.redis.io/releases/
[the root @ redis ~] # zxf the tar-4.0.14.tar.gz redis
[the root redis ~ @] redis-CD # 4.0. 14 /
[@ Redis Redis the root-4.0.14] # && the make the make the install
redis cache server (nginx + tomcat + redis + mysql realize session session sharing)
redis cache server (nginx + tomcat + redis + mysql realize session session sharing)
by the figure, we can easily see, Redis installed / usr / local, / usr / local / bin, / usr / local / share next, / usr / local / include, / usr / local / lib, / usr / local / share / man directory.

# Then switch to the next utils directory, execute redis initialization script install_server.sh, as follows:

[root@redis redis-4.0.14]# cd utils/
[root@redis utils]# ./install_server.sh 
Welcome to the redis service installer
This script will help you easily set up a running redis server

Please select the redis port for this instance: [6379] 
Selecting default: 6379
Please select the redis config file name [/etc/redis/6379.conf] 
Selected default - /etc/redis/6379.conf
Please select the redis log file name [/var/log/redis_6379.log] 
Selected default - /var/log/redis_6379.log
Please select the data directory for this instance [/var/lib/redis/6379] 
Selected default - /var/lib/redis/6379
Please select the redis executable path [/usr/local/bin/redis-server] 
Selected config: 
Port           : 6379  
Config file    : /etc/redis/6379.conf  
Log file       : /var/log/redis_6379.log
Data dir       : /var/lib/redis/6379
Executable     : /usr/local/bin/redis-server  
Cli Executable : /usr/local/bin/redis-cli
Is this ok? Then press ENTER to go on or Ctrl-C to abort.
Copied /tmp/6379.conf => /etc/init.d/redis_6379
Installing service...
Successfully added to chkconfig!
Successfully added to runlevels 345!
Starting Redis server...
Installation successful!
#上面全部默认回车就好

Through the above mounting process, we can see that after initialization redis redis profile for /etc/redis/6379.conf, the log file is stored in /var/log/redis_6379.log, data files dump.rdb / var / lib / under redis / 6379 directory, the startup script for the /etc/init.d/redis_6379.
# If you need to use systemd, you can create a file named redis_6379.service unit in the / etc / systemd / system.

[root@redis utils]# vim /etc/systemd/system/redis_6379.service
#内容如下:
[Unit]
Description=Redis on port 6379
[Service]
Type=forking
ExecStart=/etc/init.d/redis_6379 start
ExecStop=/etc/init.d/redis_6379 stop
[Install]
WantedBy=multi-user.target
#注:这里Type=forking是后台运行的形式

# Start Redis
[root @ Redis utils] # systemctl daemon-reload
[root @ Redis utils] # systemctl enable redis_6379.service
[root @ Redis utils] systemctl Start redis_6379.service #
redis cache server (nginx + tomcat + redis + mysql realize session session sharing)
# From the graph we can see that the service status is death state, the solution is to restart the service, as shown below:
redis cache server (nginx + tomcat + redis + mysql realize session session sharing)
redis cache server (nginx + tomcat + redis + mysql realize session session sharing)

#防火墙规则设置:
[root@redis utils]# firewall-cmd --add-port=6379/tcp --permanent
success
[root@redis utils]# firewall-cmd --reload
success

2) Configuration redis

[root@redis ~]# vim /etc/redis/6379.conf 
#修改内容如下(去掉注释并修改):
bind 172.16.1.30   #将redis的监听地址修改为redis主机的ip
requirepass pwd@123   #考虑到安全性,需要启动redis的密码验证功能requirepass参数。
#重新启动redis服务:
[root@redis ~]# systemctl restart redis_6379.service
[root@redis ~]# netstat -anput | grep redis
tcp        0      0 172.16.1.30:6379        0.0.0.0:*               LISTEN      12261/redis-server 

#redis profile Once configured, the operation is simple and redis start (test), as follows:

[root@redis ~]# redis-cli -h 172.16.1.30 -p 6379 -a pwd@123
Warning: Using a password with '-a' option on the command line interface may not be safe.
172.16.1.30:6379> keys *
(empty list or set)
172.16.1.30:6379> set name lisi
OK
172.16.1.30:6379> get name
"lisi"
172.16.1.30:6379> quit   

The above parameters are explained:

首先我们利用redis的命令行工具redis-cli,连接redis服务器,ip是172.16.1.30(这里就以本机进行测试),端口是6379,密码是pwd@123
keys *:是查看redis所有的键值对
set nam lisi:添加一个key(name)-value(lisi)
get name:查看name这个键值的内容
quit:退出连接
#redis的其他操作命令,会在后面讲解到

This, all redis deployment is completed, the next session tomcat configuration synchronization.

3) Configure tomcat session redis synchronization (tomcat1 same operation and tomcat2)
# download tomcat-redis-session-manager corresponding jar package, there are mainly three:

tomcat85-session-redis-1.0.jar
jedis-2.9.0.jar
commons-pool2-2.4.2.jar
① 下载完成后分别拷贝到$TOMCAT_HOME/lib目录中:
[root@tomcat-1 ~]# cp tomcat85-session-redis-1.0.jar jedis-2.9.0.jar commons-pool2-2.4.2.jar  /usr/local/tomcat8/lib/
② 修改tomcat的context.xml文件:
[root@tomcat-1 ~]# vim /usr/local/tomcat8/conf/context.xml 
添加以下内容:

redis cache server (nginx + tomcat + redis + mysql realize session session sharing)
FIG follows:

        <Valve className="com.orangefunction.tomcat.redissessions.RedisSessionHandlerValve" />
        <Manager className="com.orangefunction.tomcat.redissessions.RedisSessionManager"
        host="172.16.1.30"   #redis主机地址
        password="pwd@123"   #redis登录密码
        port="6379"        #监听端口
        database="0"   
        maxInactiveInterval="60" />    #session的失效时间(单位s)
③ 修改完,重启tomcat:
[root@tomcat-1 ~]# shutdown.sh 
[root@tomcat-1 ~]# startup.sh 
[root@tomcat-1 ~]# netstat -anput | grep 8080
tcp6       0      0 :::8080                 :::*                    LISTEN      16931/java  

Repeat tomcat-2 on the host.

④ Verify session session unanimously
# http://172.16.1.100/index.jsp simulate user access through a browser test page
first visit:
redis cache server (nginx + tomcat + redis + mysql realize session session sharing)

Second visit (to refresh the page):
redis cache server (nginx + tomcat + redis + mysql realize session session sharing)
As can be seen, respectively, visited the different tomcat, but to get the session is the same, indicating that the session session to keep pace, to achieve the purpose of the cluster.
Note: From the beginning tomcat6 session persistence is enabled by default settings, you can close the local session persistence, in fact, very simple test, in context.xml file in the tomcat's conf directory, uncomment the following section configured to:

#修改前:
    <!-- Uncomment this to disable session persistence across Tomcat restarts -->
    <!--
    <Manager pathname="" />
    -->
#修改后:
    <!-- Uncomment this to disable session persistence across Tomcat restarts -->
    <Manager pathname="" />
⑤ 查看redis:
[root@redis ~]# redis-cli -h 172.16.1.30 -p 6379 -a pwd@123
Warning: Using a password with '-a' option on the command line interface may not be safe.
172.16.1.30:6379> keys *
1) "3585F7426EBBC83802C0407575FEAC72tMLrlI.tomcat-2"
2) "name"
172.16.1.30:6379> quit

As can be seen, it redis session to session held on the tomcat2 maintain established pairs.

4, connected to the configuration database tomcat

tomcat's session by session remains redis solved this problem out, now solve the problem tomcat connection to the database. (Host 172.16.1.130 as mysql DB server)
1) install mysql service (binary)

[root@mysql ~]# vim mysql5.7.sh
#!/bin/bash
rpm -qa | grep mariadb  &> /dev/null
if [ $? -eq 0 ]
then
    rpm -e mariadb-libs --nodeps
fi
tar zxf  mysql-5.7.28-linux-glibc2.12-x86_64.tar.gz 
mv mysql-5.7.28-linux-glibc2.12-x86_64 /usr/local/mysql
ln -s /usr/local/mysql/bin/* /usr/local/bin
groupadd -r mysql && useradd -r -g mysql -s /bin/false -M mysql
mkdir /usr/local/mysql/data
chown -R mysql:mysql /usr/local/mysql
cat > /etc/my.cnf <<EOF
[mysqld]
basedir=/usr/local/mysql
datadir=/usr/local/mysql/data
pid-file=/usr/local/mysql/data/mysqld.pid
log-error=/usr/local/mysql/data/mysql.err
socket=/tmp/mysql.sock
[client]
socket=/tmp/mysql.sock
EOF
mysqld --initialize --user=mysql --basedir=/usr/local/mysql --datadir=/usr/local/mysql/data
chown -R mysql:mysql /usr/local/mysql
cd /usr/local/mysql/
cp support-files/mysql.server /etc/init.d/mysqld
chmod +x /etc/init.d/mysqld
chkconfig --add mysqld
chkconfig mysqld on
service mysqld start
mypwd=`grep password /usr/local/mysql/data/mysql.err | awk -F'root@localhost: ' '{print $2}'`
mysql -uroot -p${mypwd} -e 'alter user root@localhost identified by"123.com"' --connect-expired-password
[root@mysql ~]# sh mysql5.7.sh 
Starting MySQL. SUCCESS! 
mysql: [Warning] Using a password on the command line interface can be insecure.
[root@mysql ~]# ss -anput | grep 3306
tcp    LISTEN     0      80       :::3306                 :::*                   users:(("mysqld",pid=16753,fd=12))
#防火墙规则设置:
[root@mysql ~]# firewall-cmd --add-port=3306/tcp --permanent
success
[root@mysql ~]# firewall-cmd --reload
success

2) create the data in the database

[root@mysql ~]# mysql -uroot -p123.com
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql> grant all on *.* to javauser@'172.16.1.%' identified by 'pwd@123';   //授权一个用户
Query OK, 0 rows affected, 1 warning (0.00 sec)

mysql> flush privileges;   
Query OK, 0 rows affected (0.00 sec)

mysql> create database javadb;   //创建库
Query OK, 1 row affected (0.00 sec)

mysql> use javadb
Database changed
mysql> create table testtb(id int primary key auto_increment,
    -> name varchar(25),
    -> age int(3));   //创建表
Query OK, 0 rows affected (0.00 sec)

mysql> insert into testtb(name,age) values('zhangsan','20'),('lisi','21'),('sunqian','22');   //插入数据
Query OK, 3 rows affected (0.00 sec)
Records: 3  Duplicates: 0  Warnings: 0

mysql> select * from testtb;  #查看一下
+----+----------+------+
| id | name     | age  |
+----+----------+------+
|  1 | zhangsan |   20 |
|  2 | lisi     |   21 |
|  3 | sunqian  |   22 |
+----+----------+------+
3 rows in set (0.00 sec)

3) Configure tomcat mysql database server connection (the same operation two tomcat)

(1)下载mysql-connector-java-5.1.22-bin.jar并复制到$CATALINA_HOME/lib目录下:
[root@tomcat-1 ~]# cp mysql-connector-java-5.1.22.jar  /usr/local/tomcat8/lib/
(2)Context文件设置:
[root@tomcat-1 ~]# vim /usr/local/tomcat8/conf/context.xml

redis cache server (nginx + tomcat + redis + mysql realize session session sharing)

#上图在<Context>中添加的内容如下:
        <Resource name="jdbc/TestDB" auth="Container" type="javax.sql.DataSource"
        maxActive="100" maxIdle="30" maxWait="10000"
        username="javauser" password="pwd@123" driverClassName="com.mysql.jdbc.Driver"
        url="jdbc:mysql://172.16.1.130:3306/javadb"/>

(3) in the / web / webapp1 / root directory of the new directory for the storage site xml configuration file for tomcat mysql database connection

[root@tomcat-1 ~]# mkdir /web/webapp1/WEB-INF
[root@tomcat-1 ~]# vim /web/webapp1/WEB-INF/web.xml
添加内容如下:
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
version="2.4">
<description>MySQL Test App</description>
<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/TestDB</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
</web-app>
#保存修改并退出,重启tomcat服务:
[root@tomcat-1 ~]# shutdown.sh 
Using CATALINA_BASE:   /usr/local/tomcat8
Using CATALINA_HOME:   /usr/local/tomcat8
Using CATALINA_TMPDIR: /usr/local/tomcat8/temp
Using JRE_HOME:        /usr/local/java
Using CLASSPATH:       /usr/local/tomcat8/bin/bootstrap.jar:/usr/local/tomcat8/bin/tomcat-juli.jar
[root@tomcat-1 ~]# startup.sh 
Using CATALINA_BASE:   /usr/local/tomcat8
Using CATALINA_HOME:   /usr/local/tomcat8
Using CATALINA_TMPDIR: /usr/local/tomcat8/temp
Using JRE_HOME:        /usr/local/java
Using CLASSPATH:       /usr/local/tomcat8/bin/bootstrap.jar:/usr/local/tomcat8/bin/tomcat-juli.jar
Tomcat started.

tomcat-2 and tomcat-1 for the same operation.
(4) test code
# Now create a simple test connectivity .jsp page, the test tomcat and mysql

[root@tomcat-1 ~]# vim /web/webapp1/test.jsp
#内容如下:(根据自己的环境,修改相对应的参数)
<%@ page language="java" import="java.sql.*" pageEncoding="GB2312"%>
<html>
<head>
<title>MySQL</title>
</head>
<body>
connect MySQL<br>
<%
String driverClass="com.mysql.jdbc.Driver";
String url="jdbc:mysql://172.16.1.130:3306/javadb";
String username = "javauser";
String password = "pwd@123";
Class.forName(driverClass);
Connection conn=DriverManager.getConnection(url, username, password);
Statement stmt=conn.createStatement();
ResultSet rs = stmt.executeQuery("select * from testtb");
while(rs.next()){
out.println("<br>name:"+rs.getString(2)+"age:"+rs.getString(3));
}
rs.close();
stmt.close();
conn.close();
%>
</body>
</html>

Note: to create the same test code on the tomcat-2 nodes, but in order to better verify the title changed to "MySQL-2".

(5) accessed through a browser test page, the URL of: http://172.16.1.100/test.jsp , or reverse proxy backend tomcat server by nginx.
redis cache server (nginx + tomcat + redis + mysql realize session session sharing)
redis cache server (nginx + tomcat + redis + mysql realize session session sharing)
As can be seen from the figure, now tomcat-1 tomcat-2 and is ready to connect to the database.
This project set up is completed. . .

Installation package and jar package has been uploaded to the network disk: Link: https://pan.baidu.com/s/133H7oEbBWiBvaNWUoFgH3Q
extraction code: 2fj1

Guess you like

Origin blog.51cto.com/13972012/2477858