基於Redis的Session共享示例

在單機狀況下,Session可由部署在服務器上的Web容器來管理 (如Tomcat、JBoss)。java

在負載均衡的集羣環境下,負載均衡可能將請求分發到不一樣的服務器上去,在這種狀況,須要將有狀態的session統一管理起來。nginx

本文將給出一個簡單的示例,將session存放到Redis統一管理。由於只是一個示例,因此Nginx只用1臺,Tomcat使用2臺,Redis一個或者簡單的主從。web

環境準備

準備Redis

下載redis-3.2.3.tar.gz (Redis.io下載)redis

解壓縮redistomcat

tar -zvxf redis-3.2.3.tar.gz


 

將解壓縮後的redis文件名改爲好記點的6379 (能夠不重命名)。bash

而後使用make && make install 完成安裝。服務器

[root@dev18 redis]# mv redis-3.2.3 6379
[root@dev18 redis]# cd 6379
[root@dev18 6379]# make && make install

安裝成功以後,出現以下顯示:session

由於本版本使用的Redis版本是3.2.3, 在這個版本中,有protected mode的屬性(默認是yes),進入6379目錄,修改redis.conf配置文件。從而,其它網段的程序能夠去訪問,不然可能會出現以下的錯誤。app

Exception in thread "main" redis.clients.jedis.exceptions.JedisDataException: DENIED Redis is running in protected mode because protected mode is enabled, no bind address was specified, no authentication password is requested to clients. In this mode connections are only accepted from the loopback interface. If you want to connect from external computers to Redis you may adopt one of the following solutions: 1) Just disable protected mode sending the command 'CONFIG SET protected-mode no' from the loopback interface by connecting to Redis from the same host the server is running, however MAKE SURE Redis is not publicly accessible from internet if you do so. Use CONFIG REWRITE to make this change permanent. 2) Alternatively you can just disable the protected mode by editing the Redis configuration file, and setting the protected mode option to 'no', and then restarting the server. 3) If you started the server manually just for testing, restart it with the '--protected-mode no' option. 4) Setup a bind address or an authentication password. NOTE: You only need to do one of the above things in order for the server to start accepting connections from the outside.
	at redis.clients.jedis.Protocol.processError(Protocol.java:117)
	at redis.clients.jedis.Protocol.process(Protocol.java:151)
	at redis.clients.jedis.Protocol.read(Protocol.java:205)
	at redis.clients.jedis.Connection.readProtocolWithCheckingBroken(Connection.java:297)
	at redis.clients.jedis.Connection.getIntegerReply(Connection.java:222)
	at redis.clients.jedis.Jedis.sadd(Jedis.java:1057)
	at jedis.example.Main.main(Main.java:36)

修改後保存。負載均衡

進入src目錄,啓動Redis服務

[root@dev18 6379]# cd src
[root@dev18 src]# ./redis-server

成功啓動顯示以下:

[root@dev18 src]# ./redis-server
10051:C 22 Dec 09:50:59.653 # Warning: no config file specified, using the default config. In order to specify a config file use ./redis-server /path/to/redis.conf
                _._                                                  
           _.-``__ ''-._                                             
      _.-``    `.  `_.  ''-._           Redis 3.2.3 (00000000/0) 64 bit
  .-`` .-```.  ```\/    _.,_ ''-._                                   
 (    '      ,       .-`  | `,    )     Running in standalone mode
 |`-._`-...-` __...-.``-._|'` _.-'|     Port: 6379
 |    `-._   `._    /     _.-'    |     PID: 10051
  `-._    `-._  `-./  _.-'    _.-'                                   
 |`-._`-._    `-.__.-'    _.-'_.-'|                                  
 |    `-._`-._        _.-'_.-'    |           http://redis.io        
  `-._    `-._`-.__.-'_.-'    _.-'                                   
 |`-._`-._    `-.__.-'    _.-'_.-'|                                  
 |    `-._`-._        _.-'_.-'    |                                  
  `-._    `-._`-.__.-'_.-'    _.-'                                   
      `-._    `-.__.-'    _.-'                                       
          `-._        _.-'                                           
              `-.__.-'                                               

10051:M 22 Dec 09:50:59.656 # Server started, Redis version 3.2.3
10051:M 22 Dec 09:50:59.656 # WARNING overcommit_memory is set to 0! Background save may fail under low memory condition. To fix this issue add 'vm.overcommit_memory = 1' to /etc/sysctl.conf and then reboot or run the command 'sysctl vm.overcommit_memory=1' for this to take effect.
10051:M 22 Dec 09:50:59.656 # WARNING you have Transparent Huge Pages (THP) support enabled in your kernel. This will create latency and memory usage issues with Redis. To fix this issue run the command 'echo never > /sys/kernel/mm/transparent_hugepage/enabled' as root, and add it to your /etc/rc.local in order to retain the setting after a reboot. Redis must be restarted after THP is disabled.
10051:M 22 Dec 09:50:59.656 * The server is now ready to accept connections on port 6379

準備Tomcat

下載tomcat,並解壓縮爲兩個tomcat,並修改各自server.xml中的端口,保證二者不衝突。

本示例中,tomcat_1的端口爲8082

<Connector port="8082" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" />

tomcat_2的端口爲8083

<Connector port="8083" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" />

準備Session-Manager

你們能夠經過以下路徑獲取Session-Manager的jar包和相關的依賴包,包括common-pool2和Jedis。

https://pan.baidu.com/s/1geZVozx

下載好以後,咱們首先將這三個jar包,放到Tomcat目錄下的lib文件夾中。

配置Context.xml,添加以下內容,具體的host和port由本身的環境決定。

<Valve className="com.orangefunction.tomcat.redissessions.RedisSessionHandlerValve" />  
	<Manager className="com.orangefunction.tomcat.redissessions.RedisSessionManager"  
         host="xxx.xx.xx.xxx"  
         port="6379"  
         database="0"  
         maxInactiveInterval="60" />

而後準備一個項目,爲了方便,我直接將測試的war中的文件替換了Tomcat_Home/webapps中的ROOT的內容。也能夠經過tomcat自帶的examples示例來測試session。

如:http://localhost:8082/examples/servlets/servlet/SessionExample

至此,兩個測試的tomat就準備好了,而且已經配置了session管理,由redis來存儲。接下來,咱們就須要一個Nginx用於負載,配置兩個tomcat的信息便可。

準備Nginx

下載Nginx,解壓,而後進入Nginx的conf目錄,修改nginx.conf文件內容,找到http的部分,添加upstream,就是咱們上述提到的兩個tomcat。

http {
	upstream tomcat  {  
			server localhost:8082;  
			server localhost:8083;  
	}

本文Nginx的端口爲8899, 本身設定了一個。

server {
        listen       8899;

至此Nginx, Tomcat, Session-Manager, Redis相關的環境就所有準備好了。

接下來,要作的就是啓動Nginx, Tomcat, Redis,來看看 session是否存入到Redis中,本身的Web工程能不能正常運行等。

啓動Nginx和Tomcat

進入NGINX_HOME/使用 nginx命令啓動Nginx服務器。

進入兩個tomcat_1和tomcat_2,分別啓動tomcat。登陸本身在ROOT中放置的WEB工程,能夠看到session在Redis中存儲下來了。

經過Redis-Desktop Manager查看Redis中session的信息。

配置一個Redis從服務器

經過Redis-Desktop Manager查看Redis中session的信息。

爲上面的6379主服務器配置一個從服務器6380。

在6380的redis.conf中指定 是6379的slave,如:

slaveof 127.0.0.1 6379

啓動從服務器:

[root@dev18 src]# ./redis-server ../redis.conf 
                _._                                                  
           _.-``__ ''-._                                             
      _.-``    `.  `_.  ''-._           Redis 3.2.3 (00000000/0) 64 bit
  .-`` .-```.  ```\/    _.,_ ''-._                                   
 (    '      ,       .-`  | `,    )     Running in standalone mode
 |`-._`-...-` __...-.``-._|'` _.-'|     Port: 6380
 |    `-._   `._    /     _.-'    |     PID: 14302
  `-._    `-._  `-./  _.-'    _.-'                                   
 |`-._`-._    `-.__.-'    _.-'_.-'|                                  
 |    `-._`-._        _.-'_.-'    |           http://redis.io        
  `-._    `-._`-.__.-'_.-'    _.-'                                   
 |`-._`-._    `-.__.-'    _.-'_.-'|                                  
 |    `-._`-._        _.-'_.-'    |                                  
  `-._    `-._`-.__.-'_.-'    _.-'                                   
      `-._    `-.__.-'    _.-'                                       
          `-._        _.-'                                           
              `-.__.-'                                               

14302:S 22 Dec 12:02:55.810 # Server started, Redis version 3.2.3
14302:S 22 Dec 12:02:55.810 # WARNING overcommit_memory is set to 0! Background save may fail under low memory condition. To fix this issue add 'vm.overcommit_memory = 1' to /etc/sysctl.conf and then reboot or run the command 'sysctl vm.overcommit_memory=1' for this to take effect.
14302:S 22 Dec 12:02:55.810 # WARNING you have Transparent Huge Pages (THP) support enabled in your kernel. This will create latency and memory usage issues with Redis. To fix this issue run the command 'echo never > /sys/kernel/mm/transparent_hugepage/enabled' as root, and add it to your /etc/rc.local in order to retain the setting after a reboot. Redis must be restarted after THP is disabled.
14302:S 22 Dec 12:02:55.810 * The server is now ready to accept connections on port 6380
14302:S 22 Dec 12:02:55.810 * Connecting to MASTER 127.0.0.1:6379
14302:S 22 Dec 12:02:55.810 * MASTER <-> SLAVE sync started
14302:S 22 Dec 12:02:55.810 * Non blocking connect for SYNC fired the event.
14302:S 22 Dec 12:02:55.811 * Master replied to PING, replication can continue...
14302:S 22 Dec 12:02:55.811 * Partial resynchronization not possible (no cached master)
14302:S 22 Dec 12:02:55.815 * Full resync from master: c5038d1cbe197bbd8c8fee0e719370eac42bd6bc:1
14302:S 22 Dec 12:02:55.865 * MASTER <-> SLAVE sync: receiving 2741 bytes from master
14302:S 22 Dec 12:02:55.865 * MASTER <-> SLAVE sync: Flushing old data
14302:S 22 Dec 12:02:55.865 * MASTER <-> SLAVE sync: Loading DB in memory
14302:S 22 Dec 12:02:55.866 * MASTER <-> SLAVE sync: Finished with success

使用Redis-Desktop Manager

能夠看到,主服務6379和從服務6380都包含session的相關信息。

相關文章
相關標籤/搜索