Spring Session Redis集成(一)

来源:互联网 发布:java打字小游戏源代码 编辑:程序博客网 时间:2024/06/06 20:24

Spring Session Redis集成(一)

spring session的介绍在这就不详细讲解了,有兴趣的朋友可以查看这篇博文:

http://blog.csdn.net/admin1973/article/details/56485730

在这里就直接贴出代码,让大家以更快的方式搭建好Spring session redis环境

1.新建一个web项目gradle配置:

dependencies {    compile(            "org.springframework.session:spring-session-data-redis:1.3.0.RELEASE",            "biz.paluch.redis:lettuce:3.5.0.Final",            "org.springframework:spring-web:4.3.4.RELEASE",    )    testCompile group: 'junit', name: 'junit', version: '4.+'}
下载所需要的必须的jar!

2.新建RedisHttpSessionConfig.java代码如下:

@EnableRedisHttpSessionpublic class RedisHttpSessionConfig {    @Bean    public LettuceConnectionFactory connectionFactory() {        return new LettuceConnectionFactory();    }}

此处连接redis使用的是默认设置(本地地址,默认端口,无密码),详情请直接插看LettuceConnectionFactory.class源码!

3新建SpringSessionInitializer.java代码如下:

public class SpringSessionInitializer extends AbstractHttpSessionApplicationInitializer {    public SpringSessionInitializer() {        super(RedisHttpSessionConfig.class);    }}
4写一个测试Servlet
@WebServlet("/test")public class SpringSessionTestServlet extends HttpServlet {    protected void doPost(HttpServletRequest request,HttpServletResponse response) throws javax.servlet.ServletException, IOException {        System.out.println("hello");        System.out.println("hello");        String attributeName = request.getParameter("attributeName");        String attributeValue = request.getParameter("attributeValue");        request.getSession().setAttribute(attributeName, attributeValue);        response.sendRedirect(request.getContextPath() + "/");    }    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws javax.servlet.ServletException, IOException {        doPost(request,response);    }}
5添加一个测试页面

<body>      hello Spring Session Redis!      <form class="form-inline" role="form" action="./test" method="post">        <label for="attributeName">Attribute Name</label>        <input id="attributeName" type="text" name="attributeName"/>        <label for="attributeValue">Attribute Value</label>        <input id="attributeValue" type="text" name="attributeValue"/>        <input type="submit" value="Set Attribute"/>      </form>  </body>
现在就可以直接启动项目了

随便输入就可以在自己的redis中查看session了


如果要取session的话,和原始的方法一样,取出的就是redis里面的session

@WebServlet("/testSession")public class TestSessionServlet extends HttpServlet{    @Override    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {        HttpSession session = req.getSession();        String attributeName = session.getAttribute("lt").toString();        System.out.println(attributeName);    }    @Override    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {        doPost(req, resp);    }}

=完结=











0 0
原创粉丝点击