search
HomeBackend DevelopmentPHP Tutorialnginx+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/jcoleman

gradle 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 of

2stationtomcat, 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.2.3.

4.host='localhost'

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.}

2nginx 重新加载配置

view sourceprint?

1.nginx -s reload

八、配置Tomcat

保存的session实体是放到redis中,tomcat可以记录session-id值与redis进行对比,session-id是从cookie中取得的,不同的tomcat存储sessioncookie的位置是不同的,所以必须修改所有tomcatconf/context.xml,修改内容如下:

 sessionCookiePath="/">

九、测试结果

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 sharing

The 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.

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How can you check if a PHP session has already started?How can you check if a PHP session has already started?Apr 30, 2025 am 12:20 AM

In PHP, you can use session_status() or session_id() to check whether the session has started. 1) Use the session_status() function. If PHP_SESSION_ACTIVE is returned, the session has been started. 2) Use the session_id() function, if a non-empty string is returned, the session has been started. Both methods can effectively check the session state, and choosing which method to use depends on the PHP version and personal preferences.

Describe a scenario where using sessions is essential in a web application.Describe a scenario where using sessions is essential in a web application.Apr 30, 2025 am 12:16 AM

Sessionsarevitalinwebapplications,especiallyfore-commerceplatforms.Theymaintainuserdataacrossrequests,crucialforshoppingcarts,authentication,andpersonalization.InFlask,sessionscanbeimplementedusingsimplecodetomanageuserloginsanddatapersistence.

How can you manage concurrent session access in PHP?How can you manage concurrent session access in PHP?Apr 30, 2025 am 12:11 AM

Managing concurrent session access in PHP can be done by the following methods: 1. Use the database to store session data, 2. Use Redis or Memcached, 3. Implement a session locking strategy. These methods help ensure data consistency and improve concurrency performance.

What are the limitations of using PHP sessions?What are the limitations of using PHP sessions?Apr 30, 2025 am 12:04 AM

PHPsessionshaveseverallimitations:1)Storageconstraintscanleadtoperformanceissues;2)Securityvulnerabilitieslikesessionfixationattacksexist;3)Scalabilityischallengingduetoserver-specificstorage;4)Sessionexpirationmanagementcanbeproblematic;5)Datapersis

Explain how load balancing affects session management and how to address it.Explain how load balancing affects session management and how to address it.Apr 29, 2025 am 12:42 AM

Load balancing affects session management, but can be resolved with session replication, session stickiness, and centralized session storage. 1. Session Replication Copy session data between servers. 2. Session stickiness directs user requests to the same server. 3. Centralized session storage uses independent servers such as Redis to store session data to ensure data sharing.

Explain the concept of session locking.Explain the concept of session locking.Apr 29, 2025 am 12:39 AM

Sessionlockingisatechniqueusedtoensureauser'ssessionremainsexclusivetooneuseratatime.Itiscrucialforpreventingdatacorruptionandsecuritybreachesinmulti-userapplications.Sessionlockingisimplementedusingserver-sidelockingmechanisms,suchasReentrantLockinJ

Are there any alternatives to PHP sessions?Are there any alternatives to PHP sessions?Apr 29, 2025 am 12:36 AM

Alternatives to PHP sessions include Cookies, Token-based Authentication, Database-based Sessions, and Redis/Memcached. 1.Cookies manage sessions by storing data on the client, which is simple but low in security. 2.Token-based Authentication uses tokens to verify users, which is highly secure but requires additional logic. 3.Database-basedSessions stores data in the database, which has good scalability but may affect performance. 4. Redis/Memcached uses distributed cache to improve performance and scalability, but requires additional matching

Define the term 'session hijacking' in the context of PHP.Define the term 'session hijacking' in the context of PHP.Apr 29, 2025 am 12:33 AM

Sessionhijacking refers to an attacker impersonating a user by obtaining the user's sessionID. Prevention methods include: 1) encrypting communication using HTTPS; 2) verifying the source of the sessionID; 3) using a secure sessionID generation algorithm; 4) regularly updating the sessionID.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools