How to realize session sharing with Springboot+redis
Editor to share with you how to achieve Springboot+redis session sharing, I believe that most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to know it!
What is the cause of the problem?
When multiple applications are clustered, how to realize session sharing among applications.
Solution:
Save the session in a container and you can share it. Containers can be databases, caches, files, etc. Of course, the highest performance here is
Redis.
Example code:
1. Environment jdk1.7+ springboot1.47 + redis 3.2.0
Pom file:
Org.springframework.boot spring-boot-starter-parent 1.4.7.RELEASE UTF-8 UTF-8 1.7 org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-test Test org.springframework.boot spring-boot-starter-redis org.springframework.session spring-session-data-redis
Yml file:
# Port Settings server: port: 9999#mybatis connection Settings spring: # redis configuration redis: host: 127.0.0.1 # password: 123456 port: 6379 pool: max-idle: 100 min-idle: 1 max-active: 1000 max-wait:-1
Java Code:
Import java.util.HashMap;import java.util.Map;import javax.servlet.http.HttpServletRequest;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;import org.springframework.web.bind.annotation.RestController;@RestController@RequestMapping ("test/") public class LoginController {@ RequestMapping ("test01") @ ResponseBody public Map login (HttpServletRequest req) {Map map = new HashMap () System.out.println ("enter the project 00111111111111111111111controler"); map.put ("sessionId", req.getSession (). GetId ()); return map;}}
The second project only needs to change the port number.
First of all, my second project does not enable session sharing, then visit separately to get the following session Id
Then after opening it, let's visit it separately.
This makes it easy to achieve session sharing. Of course, this is with the help of the function encapsulated by springboot. If you use springmvc or other frameworks, you can implement it on your own. The principle is to put this session information into a common container, and then go to get it.
The above is all the content of the article "how to achieve session sharing in Springboot+redis". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!