Nginx+Tomcat builds a cluster, Spring Session+Redis realizes session sharing

Copyright statement: Please reprint this article from the source. https://blog.csdn.net/u012702547/article/details/72991283

Today, I will bring you a common architecture construction in JavaWeb, that is, Nginx+Tomcat builds a service cluster, and then realizes session sharing through Spring Session+Redis. 
To read this article, you need to have the following knowledge points: 
1. Nginx installation and configuration 
2. Spring+SpringMVC basic configuration  3. Redis
cache use 
Nginx and Redis I plan to write a few blogs to introduce later, here, if you have any understanding of these two concepts If you don't understand, you can Baidu first. If you have any questions about the use of Spring+SpringMVC, you can move to the Spring&SpringMVC framework here .

Create a Maven project and add dependencies

Use IntelliJ IDEA to create a Maven project and add related dependencies as follows:

<dependencies>
        <!-- Jedis -->
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>2.9.0</version>
        </dependency>
        <!-- Spring Data Redis -->
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-redis</artifactId>
            <version>1.8.4.RELEASE</version>
        </dependency>
        <!-- Spring Session -->
        <dependency>
            <groupId>org.springframework.session</groupId>
            <artifactId>spring-session</artifactId>
            <version>1.3.1.RELEASE</version>
        </dependency>
        <!-- Apache Commons Pool -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
            <version>2.4.2</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring-framework.version}</version>
        </dependency>
    </dependencies>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31

There are slightly more dependencies to be added here, but they can be roughly divided into the following three categories:

1. Java client of Redis, which operates Redis through Java code 
2. Spring Data Redis, which is used to simplify Redis operations 
3. Spring Session, which is used for Session management 
4. Spring

Build the Spring+SpringMVC environment

First create the spring+springmvc configuration file in the resources folder: 
write picture description here 
then configure spring and springmvc in the web.xml file, as follows:

<context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring-servlet.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

Then simply configure spring in the applicationContext.xml file, as follows:

<context:component-scan base-package="org.sang" use-default-filters="false">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
  • 1
  • 2
  • 3

Configure the annotations to be scanned by the Spring container. 
Then configure the annotations to be scanned by the SpringMVC container in spring-servlet.xml, as follows:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    <mvc:annotation-driven/>

    <context:component-scan base-package="org.sang" use-default-filters="false">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

</beans>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

The configuration of spring-servlet.xml is relatively simple. 
OK, so far, the Spring+SpringMVC environment has been successfully built.

Configure Spring Session and Redis

Session has always been a headache when we are doing clustering. There was an open source control tomcat-redis-session-manager on GitHub, but this thing only supports Tomcat7, not the best option, we can also use the one provided by Nginx ip_tables, locates the same request ip to the same server, but there is no way to make full use of the performance of the service cluster. The emergence of Spring Session can help us solve these problems very well. It has the following characteristics:

1. Spring Session provides redis, jvm map, mongo, gemfire, hazelcast, jdbc and other ways to store session containers. 
2. The same browser and the same website support multiple sessions. 
3. Does not rely on cookies. The sessionID can be passed through the header 
4. WebSocket and spring-session are combined to synchronize life cycle management. 
5. Simple to use

OK, let's take a look at how to configure our Spring Session, first add a filter in the web.xml file:

<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>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

The proxy filter provided by Spring Web is used here, and all intercepted requests are handed over to a filter named springSessionRepositoryFilter for processing. OK, then configure Spring Session and Redis in applicationContext.xml as follows:

<bean class="org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration"/>
    <bean class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
        <property name="hostName" value="192.168.248.128"/>
        <property name="port" value="6379"/>
        <property name="database" value="0"/>
    </bean>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

hostName is the address of redis, and port is the service port of redis.

OK, after writing all this is OK, let's write a simple jsp page to test, remember to start your redis service before testing.

test

The index.jsp page is as follows:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<form action="/setsession">
    <input type="text" name="name"><input type="submit" value="提交">
</form>
<form action="/getsession">
    <input type="submit" value="获取">
</form>
</body>
</html>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

I try to make this page as simple as possible. There are two buttons. The first one stores data in the session, and the second button retrieves data from the session. The corresponding Controller is as follows:

@Controller
public class HelloController {
    @RequestMapping("/setsession")
    @ResponseBody
    public void setSession(HttpSession session, String name) {
        session.setAttribute("name", name);
    }

    @RequestMapping(value = "/getsession",produces = "text/html;charset=utf-8")
    @ResponseBody
    public String getSession(HttpSession session, HttpServletRequest req) {
        return session.getAttribute("name").toString()+"-----"+req.getServletContext().getRealPath("/");
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

When I write data to httpsession, these data are automatically stored in redis cache/database. When returning the session data, I added the project deployment path to distinguish which server the request was processed by after deploying to the cluster. Start the project, the page is as follows: 
write picture description here 
Click Submit, the data will be saved in redis, as follows: 
write picture description here 
Then go back to the start page, click the Get button, you can get the value in the Session, as follows: 
write picture description here 
OK, very simple! 
So far, our Spring Session+Redis implementation of Session sharing is complete. Next, let's see how to set up a cluster for this simple web project.

Preparing to build a cluster

1. Download Nginx (address http://nginx.org/ ), the Nginx version I use here is nginx-1.12.0 
2. Download Tomcat, the Tomcat version I use here is apache-tomcat-8.5.12

The network topology diagram is as follows: 
write picture description here 
Copy the downloaded Tomcat into two copies, as follows: 
write picture description here 
Modify the Tomcat configuration file (conf/server.xml) and reset the port number. Each Tomcat server.xml needs to be modified in three places, as follows 
write picture description here 
: There are three places to modify, I will add 1 in front of the default port number, and then for the second Tomcat I will add 2 in front of the port number in these three places, so that I can run multiple on the same machine for a while. Tomcat. 
OK, after doing all this, you can start the two Tomcats to see if they can be accessed normally.

Deploy the project

OK, after both Tomcats are configured, we will copy the project just now to the webapps directory of tomcat, and copy it to both Tomcats. I won't go into details here.

Configure Nginx

Download Nginx, decompress it, and configure the conf/nginx.conf file as follows: 
write picture description here 
After the configuration is complete, start nginx. Test again.

test

Store data 
write picture description here 
in session: Fetch data from session: 
Fetch a few more times and you will see that the request is handled by a different server, as follows: 
write picture description here 
write picture description here

OK, so far, all our work is done! If you have any questions, please leave a message. Project download address:

http://download.csdn.net/detail/u012702547/9866761


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325735119&siteId=291194637