nginx+tomcat+redis는 세션 공유를 실현합니다.

WBOY
풀어 주다: 2016-08-08 09:24:04
원래의
1734명이 탐색했습니다.

nginx 현재 가장 인기 있는 오픈소스 리버스 프록시 HTTP 서버로 리소스 캐싱, 웹 서버를 구현하는 데 사용됩니다. 로드 밸런싱 및 기타 기능은 경량, 고성능, 높은 신뢰성 및 기타 특성으로 인해 인터넷 프로젝트에서 널리 사용됩니다. 관련 개념에 대한 온라인 소개가 풍부합니다. 분산형 웹서버 클러스터 배포 후 tomcat 구현을 위해서는 세션 공유 구현이 필요하다. 🎜> 서버 tomcat 클러스터 세션브로드캐스트, nginx IP 해시전략, 등 다양한 솔루션이 있습니다. nginx 끈적 모듈 및 기타 솔루션 중, 이 글에서는 주로 세션redis 서버를 사용하는 공유 솔루션을 소개합니다. 통합 스토리지 관리.

해당 애플리케이션 구조는 다음 그림을 참조합니다.

2. 환경 구성

테스트 환경은 Linux CentOS 6.5 기준입니다. , 먼저 tomcat, redis, nginx 관련 환경을 설치해 주세요. 이 글에서는 자세히 설명하지 않습니다. 테스트 구성은 다음과 같습니다.

 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

버전 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. tomcat-redis-session-manager-master

1을 기반으로 빌드되었으므로 gradle 먼저 gradle 환경을 구성해 주세요.

2, github 에서 tomcat-redis-session-manager-master를 받으세요. 소스코드, 주소는

소스보기인쇄?

1. https://github.com/jcoleman/tomcat-redis-session-manager

3, build.gradle 소스 코드 파일에서 작성자가 타사 웨어하우스(sonatype)를 사용하므로 계정을 등록해야 하는데 너무 번거롭습니다. 🎜>maven중앙 창고, 서명 관련 스크립트에 주석을 달고 종속 패키지에 대한 출력 스크립트를 추가하는 동안 copyJars (dist 디렉터리), 수정됨 build.gradle 파일은 다음과 같습니다. 소스 보기

인쇄?001.apply 플러그인: 'java'

002.apply 플러그인: 'maven'

003. 플러그인 적용: 'signing'

004.

005.group = 'com.orangefunction'

006.version = '2.0.0'

007.

008.repositories {

009.mavenCentral()

010.}

011.

012.compileJava {

013.sourceCompatibility = 1.7

014.targetCompatibility = 1.7

015.}

016. 🎜>

018.compile 그룹: 'org.apache.tomcat', 이름: 'tomcat-catalina', 버전: '7.0.27'

019.compile 그룹: 'redis.clients', 이름: 'jedis', 버전: '2.5.2'

020.compile 그룹: 'org.apache.commons', 이름: 'commons-pool2', 버전: '2.2'

021.//컴파일 그룹: 'commons-codec', 이름: 'commons-codec', 버전: '1.9'

022.

023.test컴파일 그룹: 'junit', 이름: 'junit', 버전: '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 그룹: 'org.apache.tomcat', 이름: 'tomcat-coyote ', 버전: '7.0.27'

028.}

029.

030.task javadocJar(type: Jar, presentsOn: javadoc) {

031.classifier = 'javadoc'

032.from 'build/docs/javadoc'

033.}

034. 작업 sourceJar(유형: Jar) {

036 .from sourceSets.main.allSource

037.classifier = 'sources'

038.}

039.

040.artifacts {

041.archives jar

042.

043.archives javadocJar

044.archivessourceJar

045.}

046.

047.//signing {

048.// signconfiguration.archives

049 .//}

050.

051.task copyJars(type: Copy) {

052.fromconfiguration.runtime

053.into ' dist'

054.}

055.signPom(배포) }

061.//repository(url: '

https://oss.sonatype.org/service/local/staging/deploy/ maven2/

') {

062.// 인증(사용자 이름: sonatypeUsername, 비밀번호: sonatypePassword)

063.//}

064.//repository (url: '

https://oss.sonatype.org/content/repositories/snapshots

') {

065.// 인증(사용자 이름: sonatypeUsername, 비밀번호: sonatypePassword)

066.//}

067.

068.pom.project {069.name 'tomcat-redis-session-manager'

070.packaging 'jar'

071.description 'Tomcat Redis Session Manager는 세션을 저장하기 위한 Tomcat 확장입니다. 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 이슈'

077.}

078 . >081.connection 'scm:git:

git://github.com/jcoleman/tomcat-redis-session-manager. 자식

'

082.developerConnection 'scm:git:git@github.com:jcoleman/tomcat-redis-session-manager.git'

083.}

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

'099.}

100.}

101.}

102.}

103.}

104.}

4

, gradle 명령을 실행하여 소스 코드를 빌드하고 tomcat-redis-session-manager-master 및 종속성을 컴파일 및 출력합니다. jar패키지

소스 보기

인쇄?1.gradle build -x test copyJars

모든 출력 목록 파일은 다음과 같습니다.

IV.

tomcat

구성 두 개의 장치

tomcat web

서버를 설치하고 구성합니다. 각각 Connector 포트 번호를 80809090 모두 제대로 작동하는지 확인하세요. 물론 서로 다른 호스트에 배포된 경우 동일한 포트 번호를 사용할 수 있습니다. 5. 테스트페이지 작성

2

대만tomcat 각각 페이지를 작성하고 배포용으로 패키징합니다. 1

,

tomcat_1, "tomcat_1의 응답"을 표시하고 페이지에는 현재 세션 값을 표시하고 패키지하고 게시할 수 있는 버튼이 제공됩니다. tomcat_1 서버 2,

tomcat_2에 대한 테스트 페이지 작성 , tomcat_2 "" 응답을 표시하고 페이지에는 현재 세션 값, 패키지 및 tomcat_2 서버에 게시하세요. 이때 http://10.129.221.70:8080 을 방문하세요. 및

http://10.129.221.70:9090 주소는 서로 다른 서버에 액세스하므로 각각 서로 다른 페이지 콘텐츠와 session 값은 달라야 합니다. 6. tomcat 세션 관리자 구성

tomcat-redis-session-manager-master를 사용하여 구성 수정

tomcat 세션 Manager1으로 각각 세 번째에서 생성된

tomcat-redis-session-manager-master

및 종속성 jar 패키지 표지 tomcat lib 설치 디렉터리 2를 각각 수정

2

대만 tomcat context.xml 파일, tomcat-redis-session-manager 사용 - master session 관리자 역할을 하며 redis 주소와 포트도 지정합니다. context.xml 다음 구성을 추가합니다.

소스 보기인쇄

?

1.2.3.

4.host='localhost'

5.port='6379'

6.database='0'

7.maxInactiveInterval='60' />

8.

3

,

2

스테이션 tomcat 서버를 각각 다시 시작하세요. 7. nginx 구성

1수정

기본값 .conf

구성 파일, 업스트림 로드 밸런싱 tomcat 클러스터 를 활성화하고 기본적으로 폴링을 사용합니다. 소스 보기인쇄

?

01.upstream 사이트 { ip_hash; //

ip_hash

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.위치 / {

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          끄기;   

18.proxy_set_header        호스트            $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.# 서버 오류 페이지를 정적 페이지/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.# PHP 스크립트를 127.0.0.1:80에서 수신하는 Apache에 프록시

41.#

42.#location ~.php${

43.#    proxy_pass   http://127.0.0.1;

44.#}

45. 

46.# PHP 스크립트를 127.0.0.1:9000을 수신하는 FastCGI 서버에 전달

47.#

48.#위치 ~.php${

49.#    루트           html;

50.#    fastcgi_pass   127.0.0.1:9000;

51.#    fastcgi_index  index.php;

52.#    fastcgi_param  SCRIPT_FILENAME /scripts$fastcgi_script_name;

53.#    포함        fastcgi_params;

54.#}

55. 

56.# Apache의 문서 루트

57.#는 nginx의 문서 루트

58.#

59와 일치하는 경우 .htaccess 파일에 대한 액세스를 거부합니다. #위치 ~ /.ht {

60.#    거부  모두;

61.#}

62.}

2nginx 重新加载配置

소스 보기인쇄?

1.nginx -s reload

八、配置Tomcat

保存적세션实体是放到redis中,tomcat可以记录세션 ID值与redis 进行对比,세션 ID是从쿠키中取得的, 不同的tomcat存储sessioncookie다른 방식의 位置是유tomcatconf/context.xml,修改内容如下:

 sessionCookiePath="/">

九、测试结果

1、访问 http://10.129.221.70:8080 直接请求到tomcat_1服务器,

    显示 “ tomcat_1의 응답 ”, 세션 值为'56E2FAE376A47F1C0961D722326B8423';

2, http://10.129.221.70:9090 방문 tomcat_2에 직접 요청 🎜> 서버,

표시

“response from tomcat_2” , 세션 값은 '56E2FAE376A47F1C0961D722326B8423'; 🎜>(기본값 80

포트)은 nginx 에 대한 역방향 프록시를 서버는 기본적으로 폴링 로드 방식으로 인해 페이지를 반복해서 새로 고침하여 표시되는 내용은 tomcat_1의 " 응답에 있습니다. " "tomcat_2 "의 응답이 전환되지만 세션

값은 '56E2FAE376A47F1C0961D722326B8423'; 4, redis-cli 를 사용하여 연결 redis

서버, 뷰에

세션 "56E2FAE376A47F1C0961D722326B8423" 키가 있습니다. 🎜> 데이터이고 은 직렬화된 데이터입니다. 10. 지금까지 nginx 로드 밸런싱 tomcat 클러스터 기반 세션은 일관성을 실현했습니다.

시작 순서: redis——nginx——tomcat

redis

시작 스크립트=/usr/locat/redis.2.0.1/src/redis-servernginx+tomcat+redis는 세션 공유를 실현합니다. 위 내용은 세션 공유를 구현하기 위해 nginx+tomcat+redis를 소개하고 있으며, PHP 튜토리얼에 관심이 있는 친구들에게 도움이 되길 바랍니다.

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!