Redis core principles of combat and Detailed (5) using the Spring Session and Session Redis solve cross-domain distributed share issue


Redis core principles of combat and explain (6) using the Spring Session and Session Redis solve cross-domain distributed share issue

 

Foreword

For use Nginx + Tomcat distributed load balancing, balancing algorithms are the most commonly used IP_Hash, in rotation, according to the weight, randomly. No matter which type of load balancing algorithm, due to the distribution of the different requests Nginx to one Tomcat, Tomcat at runtime are different containers, so the question session is not synchronized or loss occurs.

Session sharing program actually achieve a lot, which is a common use Tomcat, Jetty and other server provides Session sharing the Session of unified content stored in a database (such as MySQL) or cache (such as Redis) in.

This article has been learned about how to use tomcat-redis-session-manager open source project to solve the problem of cross-domain distributed session, his main idea is to use Servlet container provides plug-ins, custom creation and management of HttpSession strategy, and replace the default policy by way of configuration. tomcat-redis-session-manager rewrite org.apache.catalina.session.ManagerBase inside Tomcat particular write operation, the tomcat session storage point to the location of Redis:

Write pictures described here

RedisSessionManager inherits and overrides the org.apache.catalina.session.ManagerBase add, findSession, createEmptySession, remove the like, and deletions of the session change search operation of the pointing operation on the data storage Redis.

However, through the use *** tomcat-redis-session-manager *** should know, arranged opposite or a little cumbersome, required to artificially modify the configuration of Tomcat, the code needs to be coupled Tomcat Servlet Container like, and for the distribution of Redis cluster management is not good type of individual as opposed to the good that a framework Spring Session can truly transparent to the user to manage distributed Session.

Spring Session does not depend on Servlet container, but the code that implements the Web application level, add spring Session frame directly on the basis of the existing project to achieve Session in Redis in unified storage. If your Web application is developed in the Spring Framework, requires only a small amount of configuration of an existing project can be a stand-alone Web application changed based on a distributed application, due not based Servlet container, it can be free to migrate a project to other containers.

Spring Session use

Official Address: http://projects.spring.io/spring-session/

Official documents Address: http://docs.spring.io/spring-session/docs/1.3.0.RELEASE/reference/html5/

Spring Session provides a Servlet HttpSession creation and management of the program. Spring Session provides a cluster Session (Clustered Sessions) function defaults to external Redis to store Session data, in order to solve shared problems Session.

First, the characteristics

Spring Session offers the following features:

  1. API for implementing and managing user sessions;
  2. HttpSession - allows application container (i.e. Tomcat) HttpSession neutral alternative embodiment;
    1. Clustered Sessions - Spring Session allow cluster-session has become less burdensome, and application containers and do not bind to the gold habit.
    2. Multiple Browser Sessions - Spring Session management support multiple users in a single instance of the browser session.
    3. RESTful APIs - Spring Session session ID provided to allow headers to use RESTful API.

Two, Spring Session Case XML-based configuration to achieve

Based on a small case SSM framework.

Write pictures described here

Projects:

Write pictures described here

(1) basic environmental needs

Carried out using the Spring Session, then, first of all is to have already installed a Redis server!

(2) add project dependencies (dependencies basic use)

 <dependency>
            <groupId>org.springframework.session</groupId>
            <artifactId>spring-session-data-redis</artifactId>
            <version>1.3.0.RELEASE</version>
            <type>pom</type>
        </dependency>
        <dependency>
            <groupId>biz.paluch.redis</groupId>
            <artifactId>lettuce</artifactId>
            <version>3.5.0.Final</version>
        </dependency>
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

(3) add a Spring configuration file

After you add the necessary dependencies, we need to create the corresponding Spring configuration. Spring configuration is to create a Servlet filter, which uses Spring Session support HttpSession implementation to replace the container itself HttpSession implementation. This step is also the Spring Session of the core.

<context:annotation-config/>

<bean class="org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration"/>

<bean class="org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory"/>
 
  • 1
  • 2
  • 3
  • 4
  • 5

The code Notes:

Write pictures described here

Examples of Redis LettuceConnectionFactory is configured ConnectionFactory.

note:

<bean class="org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory"/>
 
  • 1

View the source code can be seen, the default Redis link configured to:

Write pictures described here

So, if you have your own Redis configuration, modifications such as the following configurations:

<bean class="org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory">
     <property name="hostName" value="192.168.1.149"/>
     <property name="port" value="6379"/>
     <property name="password" value="123456"/>
</bean>
 
  • 1
  • 2
  • 3
  • 4
  • 5

(5) error handling on Error creating bean with name 'enableRedisKeyspaceNotificationsInitializer':

Add the following configuration for Spring Session no longer execute config command

<util:constant static-field="org.springframework.session.data.redis.config.ConfigureRedisAction.NO_OP"/>
 
  • 1

If you do not add, it will report the following error:

Context initialization failed org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'enableRedisKeyspaceNotificationsInitializer' defined in class path resource [org/springframework/session/data/redis/config/annotation/web/http/RedisHttpSessionConfiguration.class]:
Invocation of init method failed; nested exception is java.lang.IllegalStateException: Unable to configure Redis to keyspace notifications.
See http://docs.spring.io/spring-session/docs/current/reference/html5/#api-redisoperationssessionrepository-sessiondestroyedevent
Caused by: redis.clients.jedis.exceptions.JedisDataException: ERR unknown command config
 
  • 1
  • 2
  • 3
  • 4

(5) was added in web.xml DelegatingFilterProxy

<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>
    <dispatcher>REQUEST</dispatcher>
    <dispatcher>ERROR</dispatcher>
</filter-mapping>
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

DelegatingFilterProxy looks Bean by name springSessionRepositoryFilter and convert it into the filter. For each request calls DelegatingFilterProxy, will also call springSessionRepositoryFilter.

(6) Spring MVC controller code is used for testing:

@Controller
@RequestMapping(value = "/spring/session", produces = {ConstString.APP_JSON_UTF_8})
public class SpringSessionDemoController {

    @RequestMapping(value = "/setSession.do", method = RequestMethod.GET)
    public void setSession(HttpServletRequest request, HttpServletResponse response) {
        String name = request.getParameter("name");
        String value = request.getParameter("value");
        request.getSession().setAttribute(name, value);
    }

    @RequestMapping(value = "/getSession.do", method = RequestMethod.GET)
    public void getInterestPro(HttpServletRequest request, HttpServletResponse response) {
        String name = request.getParameter("name");
        System.out.println("------" + request.getSession().getAttribute(name));
    }

    @RequestMapping(value = "/removeSession.do", method = RequestMethod.GET)
    public void removeSession(HttpServletRequest request, HttpServletResponse response) {
        String name = request.getParameter("name");
        request.getSession().removeAttribute(name);
    }
}
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

Write pictures described here

(7) Test

Use Tools to view the contents of Redis:

Write pictures described here

Can be found has been worth it! And there expirations, can see the position of the pointing arrow, the time to failure is recorded values!

(8) this, Spring Session of use has been completed!

to sum up

For cross-domain distributed environment Session sharing issue, whether used or the use of open-source framework to develop their own framework, we need to understand a problem: Create Session is a very memory-intensive things Tomcat container. Therefore, when we wrote a similar framework, we must pay attention to that, not after the Session Tomcat created for us, we first get the Session and then uploaded to the Redis and other store, but directly have our own creation Session it is essential!

 

Guess you like

Origin www.cnblogs.com/ko88/p/11697851.html