Using Idea,springboot,springsession,redis to realize session sharing of distributed micro-service

Source: Internet
Author: User
Tags redis desktop manager

The development environment: idea2016.3.4 +jdk1.8+maven3.3.9+redis+springboot+jedis

The projects in this article use MAVEN to manage project dependencies, using the combination of spring session and Redis to implement session sharing between different projects instead of the original httpsession.

Project structure:

Build Spring Boot

The pom file is as follows

<modelVersion>4.0.0</modelVersion>

<groupId>com.cky.sessionshare</groupId>
<artifactId>spring-session-share</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>

<!--Spring Boot basic Environment--
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.1.RELEASE</version>
</parent>

<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!--Spring Boot Web App Basic Environment configuration--
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>


</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
Application.java

Implement spring Boot's start main function

@SpringBootApplication
public class Application {
Automatically configure the Spring framework
public static void Main (string[] args) {
Springapplication.run (Application.class, args);
}
}
Test the test code

Create a class Helloworldcontroller for testing

@RestController
public class Helloworldcontroller {

@RequestMapping ("/index/{name}")
@ResponseBody
public string index (@PathVariable string name) {

if (null = = name) {
Name = "Boy";
}

Return "Hello World" + name;
}
}
Run Application.java to start Spring boot, visit "http://localhost:8080/index/Edison" appears on the following page, indicating that the spring boot deployment was successful

Join Spring Session Frame Pom.xml

Introducing the dependencies required by spring session and Redis

<!--spring boot and Redis application Basic Environment configuration--
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-redis</artifactId>
</dependency>

<!--spring session and Redis application Basic Environment configuration, need to turn on Redis before you can use, or start spring boot will be error-
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
</dependency>
</dependencies>

Spring Session Configuration

Create a spring configuration to create a servlet filter that supports the spring session in place of the original HttpSession implementation.

@EnableRedisHttpSession (maxinactiveintervalinseconds= 1800)
public class Sessionconfig {

@Value ("${redis.hostname:localhost}")
String HostName;

@Value ("${redis.port:6379}")
int Port;
@Bean
Public Jedisconnectionfactory ConnectionFactory () {
Jedisconnectionfactory connection = new Jedisconnectionfactory ();
return connection;
}
}

Jedisconnectionfactory

Default connection port: 6379
Default connection address: localhost
Modifications are required to modify the default port and connection address using the Jedisconnectionfactory Setport () method and the SetHostName () method

Here you can introduce configuration files to make Redis configuration more flexible to create configuration files Application.properties

Redis.homename = localhost
Redis.port = 6379

To introduce the value of a configuration file in class Sessionconfig

The modified Sessionconfig class code is as follows:

@EnableRedisHttpSession (maxinactiveintervalinseconds= 1800)
public class Sessionconfig {

@Value ("${redis.hostname:localhost}")
String HostName;

@Value ("${redis.port:6379}")
int Port;
@Bean
Public Jedisconnectionfactory ConnectionFactory () {
Jedisconnectionfactory connection = new Jedisconnectionfactory ();
Connection.setport (Port);
Connection.sethostname (HostName);

return connection;
}
}
Load Spring Session Configuration
Load the spring session configuration so that the servlet container uses our Springsessionrepositoryfilter filter on every request.
public class Sessioninitializer  extends abstracthttpsessionapplicationinitializer{
Public Sessioninitializer () {
Super (Sessionconfig.class);
}

}
Test

The above has completed the configuration of Spring Boot + spring Session +redis
Test whether you can access the same session in different containers (e.g. Tomcat), in different projects

Run Redis copy a project

The project structure is the same as the master project

modifying container ports

Modify the interface with Tomcat in spring boot
Add server.port=8090 to Application.properties

Implement session Read and write add test method main Project

Add a Testsession method to the class Helloworldcontroller in the main project
For saving and reading session
The modified code is as follows

@RestController
public class Helloworldcontroller {

@RequestMapping ("/index/{name}")
@ResponseBody
public string index (@PathVariable string name) {

if (null = = name) {
Name = "Boy";
}

Return "Hello World" + name;
}

@RequestMapping ("/tsession/{age}")
@ResponseBody
public string Testsession (HttpServletRequest req, HttpServletResponse resp, @PathVariable string age) {
Req.getsession (). SetAttribute ("Age", age);
String a = (string) req.getsession (). getattribute ("Age");

return A;
}
}
Test Project

In order to test whether the session can be read, the session of the test project does not save operations
Modifying the Testsession method in the Helloworldcontroller class of a test project
The modified code is

@RestController
public class Welcomecontroller {

@RequestMapping ("/welcome/{name}")
@ResponseBody
public string index (@PathVariable string name) {

if (null = = name) {
Name = "Edison";
}

Return "Welcome" + name;
}

@RequestMapping ("/tsession/{age}")
@ResponseBody
public string Testsession (HttpServletRequest req, HttpServletResponse resp, @PathVariable string age) {
String a = (string) req.getsession (). getattribute ("Age");
return A;
}
}
Start testing

Run the Application.java file for the main project and the test project separately

Verify

Log in to "HTTP://LOCALHOST:8080/TSESSION/88" to save the session information, as shown in the results:

Then log in to "http://localhost:8090/tsession/88" and test if you can read the previous information: If the result is, this indicates a successful test:

The Redis Desktop Manager is then used to view Redis discovery data

Use Google to view the cookies that were just delivered to the service

Optimization

If each time you create a project to write a session of the configuration, then the reusability of the code is too poor, then the session configuration separately, then only need to add a dependency in the project to implement the spring session function.

Project structure

The pom file is as follows

<?xml version= "1.0" encoding= "UTF-8"?>
<project xmlns= "http://maven.apache.org/POM/4.0.0" xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"
xsi:schemalocation= "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd" >

<modelVersion>4.0.0</modelVersion>

<groupId>com.springboot.sessionshare</groupId>
<artifactId>springbootsessionshare</artifactId>
<packaging>jar</packaging>
<version>0.0.1-SNAPSHOT</version>

<name>a Camel route</name>

<!--Spring Boot basic Environment--
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.1.RELEASE</version>
</parent>

<dependencies>
<!--Spring Boot Web App Basic Environment configuration--
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<!--spring boot and Redis application Basic Environment configuration--
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-redis</artifactId>
</dependency>

<!--spring session and Redis application Basic Environment configuration, need to turn on Redis before you can use, or start spring boot will be error-
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
</dependency>

</dependencies>

</project>
The code for the configuration class Sessionconfig and load Class Sessioninitializer has not changed before
Maven Install

Because project dependencies are managed by MAVEN, install the project into MAVEN's local repository using MAVEN install

Test creating a test project Pom.xml

Get the MAVEN location for the project you want to rely on, and the location in the Pom.xml file of the project installed to the local warehouse

To add a location to a test project

Setting up ports

server.port=8050

Other test files

The Application.java file and the Helloworldcontroller file code are the same as before, and the code is not posted here.

Start testing

Run redis-run the Application.java file in the test project-access "http://localhost:8050/tsession/100"

If the effect is consistent with the effect, the creation succeeds





Using Idea,springboot,springsession,redis to realize session sharing of distributed micro-service

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.