Spring-boot教程(八)使用Spring Session集群-redis

一、引入maven依赖

看上一篇redis的集成,redis的集成是在service模块集成的,session共享是要在web模块集成,由于service模块引入了springboot redis jar,web模块又依赖service模块,所以只需要在web模块引入

<dependency>
            <groupId>org.springframework.session</groupId>
            <artifactId>spring-session-data-redis</artifactId>
        </dependency>

二、在web模块配置application.properties

server.port=8080

# spring session使用存储类型
spring.session.store-type=redis
  • spirngboot默认就是使用redis方式,如果不想用可以填none,或者注释spring.session.store-type=redis

三、在web模块的启动类中加入@EnableRedisHttpSession  注解

package com.wqc.web;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;

@EnableCaching
@EnableRedisHttpSession  
@SpringBootApplication
public class SpringbootSessionApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootSessionApplication.class, args);
    }
}

四、编写控制器

package com.wqc.web.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping(value = "/index")
public class IndexController {

    @ResponseBody
    @RequestMapping(value = "/session")
    public Map<String, Object> getSession(HttpServletRequest request) {
        request.getSession().setAttribute("username", "admin");
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("sessionId", request.getSession().getId());
        return map;
    }

    @ResponseBody
    @RequestMapping(value = "/get")
    public String get(HttpServletRequest request) {
        String userName = (String) request.getSession().getAttribute("username");
        return userName;
    }

}

五、测试

  • 先输入http://localhost:8080/session,在session中设置一个值

  • http://localhost:8080/get,获取session中的值



  • 复制这个工程,application.properties中的server.port=8081,然后访问“http://localhost:8081/get”,如下获取到了另一个工程中设置的session的值。

 

猜你喜欢

转载自blog.csdn.net/wqc19920906/article/details/81588892