Nginx + redis (memory-type database) for session sharing, nginxredis

Source: Internet
Author: User

Nginx + redis (memory-type database) for session sharing, nginxredis

Note: Reference Original article: http://www.cnblogs.com/roy-blog/p/7196054.html

If you are interested, you can add the 481845043 java Communication Group for common progress.

1. Concept of session

In network applications, we call it "session control". In development, we often call it a session object to store the attributes and configuration information required for a specific user session. When a user jumps between Web pages of an application, the variables stored in the Session object will not be lost, but will continue to exist throughout the user Session. When a user requests a Web page from an application, if the user does not have a Session, the Web server automatically creates a Session object. When a session expires or is abandoned, the server terminates the session. The most common usage of Session objects is to store users' preferences. For example, if you specify that you do not like to view images, you can store the information in the Session object. Note: The session status is retained only in the browser that supports cookies.

2. Why session sharing?

After using nginx to achieve load balancing and dynamic/static separation, it will face a problem of memory data synchronization. We usually use data with unique identifiers, such as user information and important identifiers, memory exists. A typical method is to store data in sessions. For example, I have two Server Load balancer servers A and B. When I log on to server A and save the login data to the session, these session data only exists on server A, but not on server B. If I need to use session data when processing the next request, unfortunately, this request is handled by server B. In this case, server B may fail to obtain session data, resulting in errors. How can we share session data among all the branches of the cluster,

There are more than one Affirmative method, but the essence must be to synchronize session data on each server. Perhaps the first thought of is to use a database for data storage, however, it is actually stored in the disk of the server, but we all know that the session appears because it is in the memory, and the program reads data in the memory far faster than reading data from the disk, so we put some frequently used things in the session.

Is there a database that is stored in the memory? This is redis. In general, it is a database, but the database is stored in the memory, so the data read and write speed is much faster than the disk. Because it is a database, data synchronization can be realized. We store session data in redis, and all cluster branches can access what is in this database. This is the principle of global cache.

3 installation and running

I downloaded and tested it in a Windows Local system,:Https://github.com/msopentech/redis/releases. Redis supports 32-bit and 64-bit. Select this option based on the actual situation of your system platform. I will download it here.Redis-x64-xxx.zipCompress the package to drive E, decompress the package, and use it directly. Rename the folderRedis. The directory structure is as follows.

 

You can use the redis. windows. in the conf file, Ctrl + F find # requirepass and add your new password, such as 123, to delete the previous one, because redis does not have a password by default at the beginning. However, to ensure security, you need to set a password during development.

Decompress the package and openCmdWindow, use the cd command to switch the directory to E: \ RedisRunRedis-server.exe redis. windows. conf. If you want to make it easy, you can add the redis path to the system's environment variables, which saves you the trouble of losing the path. windows. conf can be omitted. If it is omitted, the default value is enabled. The following page is displayed:

 

 

As long as you have a style, it is enabled successfully. Note that when you close this dos window, the redis service will be closed immediately. For future convenience, you can use the redis command:

Redis-server -- service-install redis. windows. conf install it as a Windows service and set it to self-start or manual. After the installation is successful, you can find Redis in the service.

Note that you cannot change the password in the redis. windows. conf file immediately. Use the redis command redis-server -- service-stop to disable the redis service.

4. used in the project to implement global cache of session data.

1) First, add the jar package. If you are a maven project, add the following code to pom. xml:

        <dependency>            <groupId>org.springframework.session</groupId>            <artifactId>spring-session-data-redis</artifactId>            <version>1.3.1.RELEASE</version>            <type>pom</type>     </dependency>

 

If it is not a maven project, you need to add the following jar packages.

 

2) Write redis. properties with the following code:

Redis_isopen: yes # host address redis_hostName = xxx. xxx # port redis_port = 6379 # password redis_password = xxxxxxxx # connection timeout time redis_timeout = timeout = 300redis_maxActive = timeout = Success = true

 

3) write the spring-redis.xml configuration file, which configures some basic information about redis.
<? Xml version = "1.0" encoding = "UTF-8" standalone = "no"?> <Beans xmlns = "http://www.springframework.org/schema/beans" xmlns: context = "http://www.springframework.org/schema/context" xmlns: tx = "http://www.springframework.org/schema/tx" xmlns: util = "http://www.springframework.org/schema/util" xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi: schemaLocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-bea Ns. xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd "> <! -- Session sets maxInactiveIntervalInSeconds as the session expiration time, in seconds --> <bean class = "org. springframework. session. data. redis. config. annotation. web. http. redisHttpSessionConfiguration "> <property name =" maxInactiveIntervalInSeconds "value =" 3600 "> </property> </bean> <! -- Redis connection pool --> <bean id = "poolConfig" class = "redis. clients. jedis. jedisPoolConfig "> <property name =" maxIdle "value =" $ {redis_maxIdle} "/> <property name =" testOnBorrow "value =" $ {redis_testOnBorrow} "/> </bean> <! -- Redis connection factory --> <bean id = "connectionFactory" class = "org. springframework. data. redis. connection. jedis. jedisConnectionFactory "> <property name =" hostName "value =" $ {redis_hostName} "/> <property name =" port "value =" $ {redis_port} "/> <property name = "password" value = "$ {redis_password}"/> <property name = "timeout" value = "$ {redis_timeout}"/> <property name = "poolConfig" ref = "poolConfig"> </property> </bean> </beans>

4) In application. xml (spring's main configuration file), you need to add the redis. properties configuration file for scanning, as shown below.

<! -- Read redis parameter configuration --> <bean id = "propertyConfigurer" class = "org. springframework. beans. factory. config. propertyPlaceholderConfigurer "> <property name =" locations "> <list> <value>/WEB-INF/classes/redis. properties </value> </list> </property> </bean>

5) introduce the spring-redis.xml in the master configuration file as follows.

<import resource="spring-redis.xml" />

6) Add the session filter in web. xml so that the session will be manipulated by redis.

<filter>    <filter-name>springSessionRepositoryFilter</filter-name>    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>  </filter>  <filter-mapping>    <filter-name>springSessionRepositoryFilter</filter-name>    <url-pattern>/*</url-pattern>  </filter-mapping>

In this way, we will implement redis session management. PS. When you exit again, you need to write in this way to avoid errors. (Ssh Project)

public String yipinExit(){        Iterator<String>keys=session.keySet().iterator();        while(keys.hasNext()){            String key=keys.next();            session.remove(key);        }        return "yipinExit";    }

 

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.