nginx+tomcat+redis realizes session sharing
nginxAs the most popular open source reverse proxyHTTP Server, it is used to implement resource caching, web serverload balancing and other functions. Due to its lightweight, high performance, high reliability and other characteristics, it is widely used in Internet has very common applications in projects, and there are rich introductions to related concepts online. After the distributed web servercluster is deployed, it is necessary to implement sessionsharing. There are various implementation solutions for tomcat server, such as tomcat cluster session broadcast, nginx IP hash Strategy, nginx sticky module and other solutions, this article mainly introduces the sharing solution using redis server for session unified storage management.
Relevant application structure refer to the figure below:
II. Environment configuration
The test environment is based on Linux CentOS 6.5, please install tomcat, redis, first nginx related environment , without describing in detail, the test configuration of this article is as follows:
Version |
IP_Port |
|
nginx |
1.6. 2 |
10.129.221.70:80 |
tomcat_1 |
7.0.54 |
10.129.221.70:8080 |
tomcat_2 |
7.0.54 |
10.129.221.70:9090 |
redis |
2.8.19 |
10.129.221.70:6379 |
3. Build tomcat-redis-session-manager-master
1. Since the source code is built based on gradle, please configure the gradle environment first.
2, get the tomcat-redis-session-manager-master source code from github , the address is as follows:
view sourceprint ?
1. https://github.com/jcoleman/tomcat-redis-session-manager
3, find the build.gradle file in the source code, because the author uses a third-party warehouse (sonatype ), you need to register an account, which is too troublesome, just use the maven central warehouse directly after commenting, also comment the signature-related scripts and add the output script of the dependent package copyJars (dist directory), modified build.gradle The file is as follows:
view sourceprint?
001.a pply plugin: 'java'
002.apply plugin: 'maven'
003.app ly plugin: 'signing'
004.
005.group = 'com.orangefunction'
006.version = '2.0.0'
007.
008.repositories {
009.mavenCentral()
01 0. }
011.
012.compileJava {
013.sourceCompatibility = 1.7
014.targetCompatibility = 1.7
015.}
016.
017.dependencies {
018.compile group: 'org. apache.tomcat', name: 'tomcat-catalina', version: '7.0.27'
019.compile group: 'redis.clients', name: 'jedis', version: '2.5.2'
020. compile group: 'org.apache.commons', name: 'commons-pool2', version: '2.2'
021.//compile group: 'commons-codec', name: 'commons-codec', version: ' 1.9'
022.
023.testCompile group: 'junit', name: 'junit', version: '4.+'
024.testCompile 'org.hamcrest:hamcrest-core:1.3'
025. testCompile 'org.hamcrest:hamcrest-library:1.3'
026.testCompile 'org.mockito:mockito-all:1.9.5'
027.testCompile group: 'org.apache.tomcat', name: 'tomcat- coyote', version: '7.0.27'
028.}
029.
030.task javadocJar(type: Jar, dependsOn: javadoc) {
031.classifier = 'javadoc'
032.from ' build/docs/javadoc'
033.}
034.
035.task sourcesJar(type: Jar) {
036.from sourceSets.main.allSource
037.classifier = 'sources'
038. }
039.
040.artifacts {
041.archives jar
042.
043.archives javadocJar
044.archives sourcesJar
045.}
046.
047.//signing {
048.// sign configurations.archives
049.//}
050.
051.task copyJars(type: Copy) {
052.from configurations.runtime
053.into 'dist'
054.}
055.
056.uploadArchives {
057.repositories {
058.mavenDeployer {
059.beforeDeployment { MavenDeployment deployment -> signing.sign Pom(deployment)}
060.
061.//repository(url: 'https://oss.sonatype.org/service/local/staging/deploy/maven2/') {
062.// authentication(userName: sonatypeUsername, password: sonatypePassword)
063.//}
064.//repository(url: 'https://oss.sonatype.org/content/repositories/snapshots') {
065.// authentication(userName: sonatypeUsername, password: sonatypePassword)
066.//}
067.
068.pom.project {
069.name 'tomcat-redis-session-manager'
070.packaging 'jar'
071.description 'Tomcat Redis Session Manager is a Tomcat extension to store sessions in Redis'
072.url 'https://github.com/jcoleman/tomcat-redis-session-manager'
073.
074.issueManagement {
075.url 'https://github.com:jcoleman/tomcat-redis-session-manager/issues'
076.system 'GitHub Issues'
077.}
078.
079 .scm {
080.url 'https://github.com:jcoleman/tomcat-redis-session-manager'
081.connection 'scm:git:git://github.com/jcoleman/ tomcat-redis-session-manager.git'
082.developerConnection 'scm:git:git@github.com:jcoleman/tomcat-redis-session-manager.git'
083.}
084.
085.licenses {
086.license {
087.name 'MIT'
088.url 'http://opensource.org/licenses/MIT'
089.distribution 'repo'
090.}
091.}
092. 093.developers {
094.developer {
095.id 'jcoleman'
096.name 'James Coleman'
097.email 'jtc331@gmail.com'
098.url '
https:// github.com/jcolemangradle Command to build source code, compile and output
tomcat-redis-session-manager-master
and dependencies
jar
package
view source
print?1.gradle build -x test co pyJars All output list files are as follows: IV. tomcat Configuration Install and configure two tomcat web
servers, respectively modify the Connector port number to 8080
and
9090
and make sure they all work properly. Of course, you can use the same port number if distributed on different hosts. 5. Write a test page
In order to distinguish the access of2stationtomcat, write the pages separately and package them for deployment: 1, write a test page for tomcat_1, Display
"response from tomcat_1"
, and the page provides a button to display the current session value, package and publish to tomcat_1 server;
2, for Written by tomcat_2 The test page displays "response from tomcat_2", and the page provides a button to display the current session value, package and publish it to the tomcat_2 server;
At this time, visit http:// 10.129.221.70:8080 and http://10.129.221.70:9090 addresses, because they are accessing different webservers, so they display different page content and session for sure. different. 6. tomcat session manager
Configuration Modify the configuration and use tomcat-redis-session-manager-master as tomcat session manager 1, respectively The
tomcat-redis-session-manager-master and dependent jar
packages generated in three steps are covered in the lib folder 2 of the
tomcat installation directory 、 Modify the 2station tomcat ’s context.xml file respectively to use tomcat-redis-session-manager-master as the
session manager. Specify at the same time redis address and port. context.xml Add the following configuration: view sourceprint?1.
5.port='6379'6.database ='0'
7.maxInactiveInterval='60' />8.3, respectively restart the
2
station
tomcat
servers.
Seven,nginx
Configure
1, modify default.conf configuration file, enable upstream load balancing tomcat Cluster
, polling mode is used by default. view source
print?01.upstream site { ip_hash; //based on ip_hashdistribution 02.server localhost:8080;
03.server localhost :9090;04.} 05. 06.server {
07.listen 80;08.server_name localhost;
09.
10.#charset koi8-r;
11.#access_log /var/log/nginx/log/host.access.log main;
12.
13.location / {
14.#root /usr/share/nginx/html;
15.#index index.html index.htm;
16.index index_tel.http://www.it165.net/pro/webjsp/" target="_blank"class="keylink">jsp index.http://www.it165.net/pro/webjsp/"target="_blank" class="keylink">jsp index.html index.htm ;
17.proxy_redirect off;
18.proxy_set_header Host $host;
19.proxy_set_header X-Real-IP $remote_addr;
20.proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
21.client_max_body_size 10m;
22.client_body_buffer_size 128k;
23.proxy_buffers 32 4k;
24.proxy_connect_timeout 3;
25.proxy_send_timeout 30;
26.proxy_read_timeout 30;
27.proxy_pass http://site;
28.
29.}
30.
31.#error_page 404 /404.html;
32.
33.# redirect server error pages to the static page /50x.html
34.#
35.error_page 500 502 503 504 /50x.html;
36.location = /50x.html {
37.root /usr/share/nginx/html;
38.}
39.
40.# proxy the PHP scripts to Apache listening on 127.0.0.1:80
41.#
42.#location ~ .php$ {
43.# proxy_pass http://127.0.0.1;
44.#}
45.
46.# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
47.#
48.#location ~ .php$ {
49.# root html;
50.# fastcgi_pass 127.0.0.1:9000;
51.# fastcgi_index index.php;
52.# fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
53.# include fastcgi_params;
54.#}
55.
56.# deny access to .htaccess files, if Apache's document root
57.# concurs with nginx's one
58.#
59.#location ~ /.ht {
60.# deny all;
61.#}
62.}
2、nginx 重新加载配置
view sourceprint?
1.nginx -s reload
八、配置Tomcat
保存的session实体是放到redis中,tomcat可以记录session-id值与redis进行对比,session-id是从cookie中取得的,不同的tomcat存储sessioncookie的位置是不同的,所以必须修改所有tomcat中conf/context.xml,修改内容如下:
九、测试结果
1、访问 http://10.129.221.70:8080 直接请求到tomcat_1服务器,
显示 “ response from tomcat_1 ”, session 值为 ‘56E2FAE376A47F1C0961D722326B8423’;
2、Visit http://10.129.221.70:9090 Direct request to tomcat_2server,
Display“response from tomcat_2” , session value is '56E2FAE376A47F1C0961D722326B8423';
3, visit http://10.129.221.70 (default 80port) request to nginx reverse proxy to the specified Webserver, due to the default polling load method,
The content displayed by repeatedly refreshing the page switches between "response from tomcat_1" and "response from tomcat_2", but session The value remains as '56E2FAE376A47F1C0961D722326B8423';
4, use redis-cli to connect redis server, it will show that there is "56E2FAE376A47F1C0961D722326B8423" key session data, value is serialized data.
10. At this point, the session consistency of the tomcat cluster based on nginxload balancing has been achieved.
Startup sequence: redis——nginx——tomcat
redisStartup script=/usr/locat/redis.2.0.1/src/redis-server
nginx+tomcat+redis realizes session sharingThe above introduces nginx+tomcat+redis to realize session sharing, including the relevant content. I hope it will be helpful to friends who are interested in PHP tutorials.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Redis cluster mode deploys Redis instances to multiple servers through sharding, improving scalability and availability. The construction steps are as follows: Create odd Redis instances with different ports; Create 3 sentinel instances, monitor Redis instances and failover; configure sentinel configuration files, add monitoring Redis instance information and failover settings; configure Redis instance configuration files, enable cluster mode and specify the cluster information file path; create nodes.conf file, containing information of each Redis instance; start the cluster, execute the create command to create a cluster and specify the number of replicas; log in to the cluster to execute the CLUSTER INFO command to verify the cluster status; make

How to clear Redis data: Use the FLUSHALL command to clear all key values. Use the FLUSHDB command to clear the key value of the currently selected database. Use SELECT to switch databases, and then use FLUSHDB to clear multiple databases. Use the DEL command to delete a specific key. Use the redis-cli tool to clear the data.

To read a queue from Redis, you need to get the queue name, read the elements using the LPOP command, and process the empty queue. The specific steps are as follows: Get the queue name: name it with the prefix of "queue:" such as "queue:my-queue". Use the LPOP command: Eject the element from the head of the queue and return its value, such as LPOP queue:my-queue. Processing empty queues: If the queue is empty, LPOP returns nil, and you can check whether the queue exists before reading the element.

On CentOS systems, you can limit the execution time of Lua scripts by modifying Redis configuration files or using Redis commands to prevent malicious scripts from consuming too much resources. Method 1: Modify the Redis configuration file and locate the Redis configuration file: The Redis configuration file is usually located in /etc/redis/redis.conf. Edit configuration file: Open the configuration file using a text editor (such as vi or nano): sudovi/etc/redis/redis.conf Set the Lua script execution time limit: Add or modify the following lines in the configuration file to set the maximum execution time of the Lua script (unit: milliseconds)

Use the Redis command line tool (redis-cli) to manage and operate Redis through the following steps: Connect to the server, specify the address and port. Send commands to the server using the command name and parameters. Use the HELP command to view help information for a specific command. Use the QUIT command to exit the command line tool.

There are two types of Redis data expiration strategies: periodic deletion: periodic scan to delete the expired key, which can be set through expired-time-cap-remove-count and expired-time-cap-remove-delay parameters. Lazy Deletion: Check for deletion expired keys only when keys are read or written. They can be set through lazyfree-lazy-eviction, lazyfree-lazy-expire, lazyfree-lazy-user-del parameters.

In Debian systems, readdir system calls are used to read directory contents. If its performance is not good, try the following optimization strategy: Simplify the number of directory files: Split large directories into multiple small directories as much as possible, reducing the number of items processed per readdir call. Enable directory content caching: build a cache mechanism, update the cache regularly or when directory content changes, and reduce frequent calls to readdir. Memory caches (such as Memcached or Redis) or local caches (such as files or databases) can be considered. Adopt efficient data structure: If you implement directory traversal by yourself, select more efficient data structures (such as hash tables instead of linear search) to store and access directory information

Redis counter is a mechanism that uses Redis key-value pair storage to implement counting operations, including the following steps: creating counter keys, increasing counts, decreasing counts, resetting counts, and obtaining counts. The advantages of Redis counters include fast speed, high concurrency, durability and simplicity and ease of use. It can be used in scenarios such as user access counting, real-time metric tracking, game scores and rankings, and order processing counting.
