Tomcat + nginx + redis for load balancing and session sharing (2)

Source: Internet
Author: User
Tags download redis redis desktop manager

Today, we will continue to talk about the last part of session sharing. If you have not read the previous part, you can first read the previous part, http://www.cnblogs.com/zhrxidian/p/5432886.html.

 

1. redis introduction and download and Installation

As the main character, I believe everyone should be impressed with redis. redis is an open-source high-performance Key-value database with a wide range of key-value Storage types, it also provides APIs in multiple languages.

Unlike General databases, redis uses memory as the primary storage, while hard disks for data persistence. redis periodically writes data to the hard disk. This means that once the server is powered off or restarted, data may be lost, so we do not recommend using redis to store key data. Of course, because redis uses memory for reading and writing data, it is very fast and suitable for storing some temporary data.

In addition, redis has many functions, such as queue and cache, but I have never used it. I cannot explain it here, however, this does not affect the session sharing function today.

 

First, download redis. This is the Windows version of https://github.com/servicestack/redis-windows.

You can click on the right side to download all the files, but it feels unnecessary and the download speed is slow. We recommend you go to downloads to download the redis package we need.

 

 

Redis is free of installation in windows. After the download is complete, unzip the package and copy the folder to your own drive. This is what it looks like after decompression.

Redis does not require a password by default at the beginning. If you want to set a password, you can enter redis. windows. find requirepass In the conf file, delete the # sign in front of it, and set the password after it. Here I set it to 123456.

Next we open redis. Open the redis. Windows. conf file first. The following interface is displayed. (Redis-server.exe can be opened, but the configuration file will not be loaded ).

 

In addition, like other databases, we need to install a secondary visualization tool redis Desktop Manager, which is http://redis?top.com/download.

We downloaded the Windows version. After the installation is complete, there are no connection objects, so let's add one for it. Click Connect to redis server below. A pop-up box is displayed. Then we can enter the name at will. Host is added to the IP address of our redis server. You can enter localhost directly locally. The default port is 6379, and Auth is the password, which is not required, if no password is set, click OK.

So far, our preparations have been completed. Next we will start our integration of spring and redis.

 

2. Spring and redis Integration

This is my project directory at the end of the previous article.

In fact, spring itself provides support for redis, that is, spring-session. We only need to put this in pom. add the following code in XML, and MAVEN will download the required jar package and dependency package.

 

1 <dependency>2       <groupId>org.springframework.session</groupId>3       <artifactId>spring-session-data-redis</artifactId>4       <version>1.1.1.RELEASE</version>5       <type>pom</type>6 </dependency>

Then we create a new redis. properties in the resources folder and add the following content to it.

 

 

Create a new spring-redis.xml and add the redis-related configuration to it. Maxinactiveintervalinseconds sets the session validity period in seconds. However, no matter how it is set, the actual validity period of the session will be slightly longer than we set.

1 <? XML version = "1.0" encoding = "UTF-8"?> 2 <beans xmlns = "http://www.springframework.org/schema/beans" 3 xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" 4 xsi: schemalocation = "http://www.springframework.org/schema/beans 5 http://www.springframework.org/schema/beans/spring-beans.xsd"> 6 7 <! -- Session settings --> 8 <Bean class = "org. springframework. session. data. redis. config. annotation. web. HTTP. redishttpsessionconfiguration "> 9 <property name =" maxinactiveintervalinseconds "value =" 3600 "> </property> 10 </bean> 11 <! -- Redis connection pool --> 12 <bean id = "poolconfig" class = "redis. Clients. Jedis. jedispoolconfig"/> 13 14 <! -- Redis connection factory --> 15 <bean id = "connectionfactory" class = "org. springframework. data. redis. connection. jedis. jedisconnectionfactory "> 16 <property name =" hostname "value =" $ {redis_hostname} "/> 17 <property name =" Port "value =" $ {redis_port} "/> 18 <property name = "password" value = "$ {redis_password}"/> 19 <property name = "timeout" value = "$ {redis_timeout}"/> 20 <property name = "poolconfig" ref = "poolconfig"> </property> 21 </bean> 22 23 24 25 </beans>

After adding the file, do not forget to introduce the newly added file in spring. XML and Web. xml. The Code will not be provided here.
Finally, we need to add the spring session filter to Web. xml. I personally understand that this filter is used to tell spring to take over session management and creation.

1 <! -- Session filter --> 2 <filter> 3 <filter-Name> springsessionrepositoryfilter </filter-Name> 4 <filter-class> Org. springframework. web. filter. delegatingfilterproxy </filter-class> 5 </filter> 6 <filter-mapping> 7 <filter-Name> springsessionrepositoryfilter </filter-Name> 8 <URL-pattern>/* </url-pattern> 9 </filter-mapping>

After this step is completed, we have completed the integration of redis. Next we will test it.

3. Session sharing Test

To complete the test, I first added two simple methods in indexcontroller: one is the logon method and the other is the user center method. Note that if you want to save objects to redis, You need to serialize the objects to save them. For convenience, I used fastjson to convert the object into a string and store it for convenience.

 

In addition, the personal Center page is very simple.

Now all the work before the test has been completed. Start the test.

Start cmdat1 and enter localhost: 8080 in the browser to go to our logon page. The logon Page code will not be pasted, and Ajax is submitted. Enter our user name and password. Log on. We can see that we have successfully logged on, and the user's personal center can successfully display our user name.

Let's look at our redis server. We can see that some data has been added in it, and some sessions have been added by spring. I am not very clear about what it means, but let's look at it, you can find the session we just added. In the upper-right corner, Til is the remaining validity time of our session.

Can this session be shared? Let's copy the project of tomcat1 to tomcat2 and modify individual words to differentiate pages.

Start the project and enter the personal center path in the browser, localhost: 8081/usercenter. You can see that no NULL pointer error is reported, and you can directly go to the personal Center page (of course, in the same browser ). Shared successfully.

 

Next, open the nginx we configured last time, go to the logon page, and perform the logon steps. We can see that we may log on to Tomcat 1 and go to the personal center of Tomcat 2. Of course, the opposite may be true, when refreshing the personal Center page, the two Tomcat pages are displayed at intervals and the test is successful.

Add one that was missed last time. In this case, we can close one of the servers. I shut down tomcat1 and refresh the page multiple times. We will find that the next page appears at tomcat2, which is inevitable, but sometimes fast, sometimes slow. The reason is that when nginx forwards the request to Tomcat 2, the server can certainly make an immediate response. However, if it is transferred to Tomcat 1, a response wait process lasting more than one minute will appear, this is obviously unacceptable. To do this, we need to write and modify the ngin configuration. Here we will introduce several labels.

  • Proxy_connect_timeout: the timeout time for connecting to the server. The default value is 60 s.
  • Fail_timeout: if the server does not respond within this time period, the server is considered invalid. The default value is 10 s.
  • Max_fails: number of failed connections allowed. The default value is 1.

Here we need to wait for the time = proxy_connect_timeout + fail_timeout * max_fails, so I only need to wait 3 seconds for the following configuration, nginx will forward the request to Tomcat 2, which is still within the acceptable range.

 

 

 

 4. Summary

All in all, spring has provided good support for our session sharing. We only need to make good use of it.

For the demo source code, visit http://download.csdn.net/detail/zhrxidian/9520968.

 

5. Postscript

If you encounter a problem the other day, you can set a scheduling task, but you cannot set the same time point. In this way, you need to save the time set before. The idea at that time was to create a new table to store the set time, but there was always a sense of cool-killing. Later, the foreman reminded the project that redis was ready for use, and the project was called to implement the data cache function.

Fortunately, redis provides a Java client Development Kit named "Jedis", which will be busy next week. After a while, we will share the process of using Jedis to cache data.

 

You are welcome to reprint it, but please allow it first.

 

Tomcat + nginx + redis for load balancing and session sharing (2)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.