在现代网络服务中,session(会话)不得不说是非常重要也是一定要实现的概念,因此在web后台开发中,对session的管理和维护是必须要实现的组件。这篇文章主要是介绍如何在spring boot项目中加入redis来实现对session的存储与管理。
1. 利用spring initializr来新建一个spring boot项目
2. 在pom.xml中添加redis和session的相关依赖。项目生成的时候虽然也会自动生成父依赖,但是1.5.3版本的spring boot的redis相关依赖有可能不能够正常工作,笔者自行在maven repository找到了比较稳定的版本如下方代码所示
<dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-web</artifactid> </dependency> <dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-data-redis</artifactid> <version>1.5.2.release</version> </dependency> <dependency> <groupid>org.springframework.session</groupid> <artifactid>spring-session-data-redis</artifactid> <version>1.3.0.release</version> </dependency>
3. 在application.properties中添加redis数据库的相关配置。这里为了演示使用方法只添加了相对简单的配置,即设置了session存储的数据库类型、使用的数据库号、数据库地址和端口号。实战中还会对使用非默认数据库、数据库大小、数据库最大连接数、生存时长、是否写回磁盘等许多参数进行配置
# redis配置 spring.session.store-type=redis spring.redis.database=0 spring.redis.host=localhost spring.redis.port=6379
4. 编写一个测试的controller来验证是否能够正确地读写session。这里的controller中,我判断了当前获取的session是否是新生成的。如果是,则输出成功创建一个session对象,并返回session的id,然后在session中添加一个字段。如果session不是新生成的,即是已经存在的session,则输出session是已经存在的并返回session的id,然后再输出session中初次创建session保存的key所对应的value
@springbootapplication @enableredishttpsession @restcontroller public class demoapplication { private logger logger = loggerfactory.getlogger(this.getclass()); public static void main(string[] args) { springapplication app = new springapplication(demoapplication.class); app.setwebenvironment(true); app.run(args); } @getmapping("/hello") public responseentity<?> hello(httpsession session) { if (session.isnew()) { logger.info("successfully creates a session ,the id of session :" + session.getid()); session.setattribute("key", "hello"); } else { logger.info("session already exists in the server, the id of session :"+ session.getid()); logger.info(session.getattribute("key").tostring()); } return new responseentity<>("hello world", httpstatus.ok); } }
5. 测试代码
首先运行redis客户端
redis-cli
查看当前数据库内容
127.0.0.1:6379> keys * (empty list or set)
运行spring boot项目
第一次浏览器访问localhost:8080/hello,如下图所示则成功运行
查看log可以看到
2017-06-12 00:26:12.601 info 9580 — [nio-8080-exec-1] ication$$enhancerbyspringcglib$$de942542 : successfully creates a session ,the id of session :4368a535-9bfa-406b-975c-e58c2bca1e75
再次访问localhost:8080/hello时,查看log可以看到能够正确地从redis中取出存放在session中的某个key对应的值
2017-06-12 00:30:43.533 info 9580 — [nio-8080-exec-5] ication$$enhancerbyspringcglib$$de942542 : session already exists in the server, the id of session :4368a535-9bfa-406b-975c-e58c2bca1e75 2017-06-12 00:30:43.533 info 9580 — [nio-8080-exec-5] ication$$enhancerbyspringcglib$$de942542 : hello
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。
如对本文有疑问, 点击进行留言回复!!
springmvc之ResponseBody响应json数据遇到的错误及解决
uni-app 后台升级 静默升级 uniapp 后台更新 静默更新 在线升级
SpringBoot多Module启动报错Could not transfer metadata
Hibernate项目报错:Cannot call sendError() after the response has been committed
网友评论