This time I bring a tutorial on spring boot + redis to achieve session sharing.
In the spring boot documentation, we are told to add @EnableRedisHttpSession to enable spring session support. The configuration is as follows:
The annotation @EnableRedisHttpSession is provided by spring-session-data-redis, so add it in the pom.xml file:
Next, you need to configure the location of the redis server in application.properties. Here, we use this machine:
In this way, the simplest spring boot + redis to achieve session sharing is completed, and the next test is performed.
First, we open two tomcat services, the ports are 8080 and 9090, and set them in application.properties :
Next define a Controller:
启动之后进行访问测试,首先访问8080端口的tomcat,返回 :
接着,我们访问8080端口的sessions,返回:
最后,再访问9090端口的sessions,返回:
可见,8080与9090两个服务器返回结果一样,实现了session的共享
如果此时再访问9090端口的first的话,首先返回:
而两个服务器的sessions都是返回:
通过spring boot + redis来实现session的共享非常简单,而且用处也极大,配合nginx进行负载均衡,便能实现分布式的应用了。
本次的redis并没有进行主从、读写分离等等配置(_(:з」∠)_其实是博主懒,还没尝试过.......)
而且,nginx的单点故障也是我们应用的障碍......以后可能会有对此次博客的改进版本,比如使用zookeeper进行负载均衡,敬请期待。