java redis session共享实现,Springboot集成Spring session利用redis来实现session共享

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.xml文件中添加:

org.springframework.boot

spring-boot-starter-redis

org.springframework.session

spring-session-data-redis

还有一个地方需要注意Pom.xml除了要添加以上依赖还需添加如下配置:

redis.clients

jedis

2.9.0

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 firstResp(HttpServletRequest request){

Map 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 Object sessions (HttpServletRequest request){

Map map = new HashMap<>();

map.put("sessionId" ,request.getSession().getId());

map.put("message" , request.getSession().getAttribute("map"));

return map ;

}

}

{"request Url":"http://127.0.0.1:8080/admin/redis/first"}

{"sessionId":"9ff88ad6-90fa-49aa-86a3-a3c8fc155eed","message":null}

{"request Url":"http://127.0.0.1:9090/admin/redis/first"}

{"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 后面多了两个空格 各种找问题,去掉启动正常

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值