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的值。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值