1.在spring boot的文档中,告诉我们添加@EnableRedisHttpSession来开启spring session支持,配置如下:
@SpringBootApplication
@EnableRedisHttpSession
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
2.而@EnableRedisHttpSession这个注解是由spring-session-data-redis提供的,所以在pom. 文件中添加:
<dependency>
<groupId>org.spring work.boot</groupId>
<artifactId>spring-boot-starter-redis</artifactId>
</dependency>
<dependency>
<groupId>org.spring work.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
</dependency>
还有一个地方需要注意Pom. 除了要添加以上依赖还需添加如下配置:
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
3.接下来,则需要在application.properties中配置redis服务器的位置了,在这里,我们就用本机:
spring.redis.host=127.0.0.1
spring.redis.port=6379
这样以来,最简单的spring boot + redis实现session共享就完成了
如下是进行测试:
1.首先把tomcat的端口修改为8080
server.port=8080
2.新建Contrller
@RestController
@RequestMapping(value = \"/admin/redis\")
public class SessionController {
@RequestMapping(value = \"/first\" , method = RequestMethod.GET)
public Map<String , > firstResp(HttpServletRequest request){
Map<String , > map = new HashMap<>();
request.getSession().setAttribute(\"request Url\" , request.getRequestURL());
map.put(\"request Url\" , request.getRequestURL());
return map;
}
@RequestMapping(value = \"sessions\" , method = RequestMethod.GET)
public sessions (HttpServletRequest request){
Map<String , > map = new HashMap<>();
map.put(\"sessionId\" ,request.getSession().getId());
map.put(\"message\" , request.getSession().getAttribute(\"map\"));
return map ;
}
}
3.启动之后访问8080端口Tomcat:http://127.0.0.1:8080/admin/redis/first
{\"request Url\":\"http://127.0.0.1:8080/admin/redis/first\"}
4.接着,我们访问8080端口的sessions :http://127.0.0.1:8080/admin/redis/sessions
{\"sessionId\":\"9ff88ad6-90fa-49aa-86a3-a3c8fc155eed\",\"message\":null}
5.然后启动9090端口Tomcat:http://127.0.0.1:9090/admin/redis/first
{\"request Url\":\"http://127.0.0.1:9090/admin/redis/first\"}
6.最后我们访问9090端口的sessions :http://127.0.0.1:9090/admin/redis/sessions
{\"sessionId\":\"9ff88ad6-90fa-49aa-86a3-a3c8fc155eed\",\"message\":null}
可见,8080与9090两个服务器返回结果一样,实现了session的共享
其中问题:
启动项目的时候回出现
Cannot get Jedis connection; nested exception is redis.clients.jedis.exceptions.JedisConnectionException: java.net.UnknownHostException: 127.0.0.1
后面发现是 spring.redis.host=127.0.0.1 host 后面多了两个空格 各种找问题,去掉启动正常
继续阅读与本文标签相同的文章
5G套餐今天出炉,好似并不友好!
-
猫和老鼠:5种药水效果可以叠加吗?这2种药水效果会有冲突!
2026-05-18栏目: 教程
-
自媒体教程,深度剖析平台的推荐机制原理,了解怎么获取高流量
2026-05-18栏目: 教程
-
宽带故障怎么办?教你几招,轻松解决!
2026-05-18栏目: 教程
-
Python 3.8刚刚发布!一分钟了解新版本的强大功能!
2026-05-18栏目: 教程
-
《中国工夫》聚焦“中国智造”
2026-05-18栏目: 教程
