热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

架构实战篇(十二):SpringBoot分布式Session共享Redis

分布式Web网站一般都会碰到集群session共享问题,小编整理了一套解决方案,内附GitH

项目整体结构


一、maven 依赖

这边依赖的是spring boot 1.5.10 版本,2.x的版本session方法有做修改,不过用法没变

xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

   <modelVersion>4.0.0modelVersion>

   <groupId>com.ituniongroupId>
   <artifactId>spring-boot-redis-sessionartifactId>
   <version>0.0.1-SNAPSHOTversion>
   <packaging>jarpackaging>
   <name>spring-boot-redis-sessionname>
   <description>spring boot redis sessiondescription>
   <parent>
       <groupId>org.springframework.bootgroupId>
       <artifactId>spring-boot-starter-parentartifactId>
       <version>1.5.10.RELEASEversion>
       <relativePath/>
   parent>
   <properties>
       <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
       <project.reporting.outputEncoding>UTF-8project.reporting.outputEncoding>
       <java.version>1.8java.version>
   properties>
   <dependencies>
       <dependency>
           <groupId>org.springframework.bootgroupId>
           <artifactId>spring-boot-starter-webartifactId>
       dependency>
       <dependency>
           <groupId>org.springframework.sessiongroupId>
           <artifactId>spring-session-data-redisartifactId>
       dependency>
       <dependency>
           <groupId>org.springframework.bootgroupId>
           <artifactId>spring-boot-devtoolsartifactId>
           <scope>runtimescope>
       dependency>
   dependencies>
   <build>
       <plugins>
           <plugin>
               <groupId>org.springframework.bootgroupId>
               <artifactId>spring-boot-maven-pluginartifactId>
           plugin>
       plugins>
   build>project>


二、配置内容

默认给项目配置的是debug级别的日志,如果不需要看到可以修改成info或者error

spring.redis.host=localhost
spring.redis.port=6379
spring.redis.password=
spring.redis.database=0
logging.level.root=info
logging.level.com.itunion=debug


三、程序入口

package com.itunion;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplicationpublic class SpringBootRedisSessionApplication {    
   public static void main(String[] args) {
       SpringApplication.run(SpringBootRedisSessionApplication.class, args);
   }
}


四、实体类

用户类字段简单写了几个,昵称,从哪里登录的,会话编号token

package com.itunion.model;
import java.io.Serializable;
public class User implements Serializable {    
   private String nickName;    
   private String loginBy;    
   private String token;    
   public User(String nickName, String loginBy, String token) {            this.nickName = nickName;        
       this.loginBy = loginBy;        
       this.token = token;
   }  
   // 省略get , set 方法
   @Override
   public String toString() {        
       return "User{" +                "nickName='" + nickName + '\'' +                ", loginBy='" + loginBy + '\'' +                ", token='" + token + '\'' +                '}';
   }
}


五、登录控制层

模拟了普通的账号密码登录,微信code方式登录,从session中获取用户信息,退出登录接口

登录成功需要把sessionId 返回到前端,退出需要调用session的invalidate 方法

package com.itunion.controller;
import com.itunion.model.Result;
import com.itunion.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpSession;
@RestController@RequestMappingpublic class LoginController {    
@Autowired
   private HttpSession session;    
   // 账号密码登录
   @GetMapping(value = "login")    
   public Result login(@RequestParam String username, @RequestParam String password) {
       System.out.println("login username = [" + username + "], password = [" + password + "]");
       User user = new User(username, "app", session.getId());
       session.setAttribute("user", user);        
       // 这里记得把会话ID返回到前端,前端之后请求都需要携带该ID, 可以封装到对象中
       return new Result<>(user);
   }    
   // 微信登录
   @GetMapping(value = "loginByWx")    
   public Result loginByWx(@RequestParam String code) {
       System.out.println("loginByWx.code = [" + code + "]");                // 调用微信API获取OpenId等信息
       User user = new User("Jim", "weixin", session.getId());
       session.setAttribute("user", user);        
       return new Result<>(user);
   }    
   // 退出
   @GetMapping(value = "logout")    
   public Result logout() {
       System.out.println("logout");        
       // session 设置为无效的
       session.invalidate();        
   return new Result();
   }    
   // 使用会话中的信息
   @GetMapping(value = "hello")    
   public Result hello() {
       User user = (User) session.getAttribute("user");
       System.out.println("hello " + user.toString());        
       return new Result<>(user);
   }
}


六、实现ExpiringSession会话类

因为 SessionRepositoryFilter 拦截器自动注入的是 ExpiringSession 类型的Session 如果你只是实现了Session接口将会报错,所以这边实现的 ExpiringSession 接口


又因为 redis 会自动销毁 session ,所以不需要对time相关方法做具体实现

同时用JsonIgnore 忽略不需要序列化的字段防止反序列化失败

package com.itunion.config.session;
import com.fasterxml.jackson.annotation.JsonIgnore;
import org.springframework.session.ExpiringSession;
import java.io.Serializable;
import java.util.HashMap;import java.util.Map;
import java.util.Set;
import java.util.UUID;
/**
* 因为Filter 拦截器自动注入的是 ExpiringSession 类型的Session
* 所以这边实现的 ExpiringSession 方法可以不用管,用JsonIgnore 忽略防止反序列化失败
*/
public
class WxRedisSession implements ExpiringSession, Serializable {    
   private String id;    
   private Map sessiOnAttrs= new HashMap();    
   public WxRedisSession() {        
       this(UUID.randomUUID().toString().replace("-", ""));
   }    
   public WxRedisSession(String id) {        
       this.id = id;
   }    
   @Override
   public String getId() {        
       return id;
   }    
   
   @Override

   public T getAttribute(String attributeName) {        
       return (T) this.sessionAttrs.get(attributeName);
   }    
   @JsonIgnore
   @Override
   public Set getAttributeNames() {        
       return this.sessionAttrs.keySet();
   }    
   @Override
   public void setAttribute(String attributeName, Object attributeValue) {        
       if (attributeValue == null) {
           removeAttribute(attributeName);
       } else {            
           this.sessionAttrs.put(attributeName, attributeValue);
       }
   }        
   @Override
   public void removeAttribute(String attributeName) {        
       this.sessionAttrs.remove(attributeName);
   }    
   public void setId(String id) {        
       this.id = id;
   }    
   //   反序列化需要用到get set方法
   public Map getSessionAttrs() {        
       return sessionAttrs;
   }    
   public void setSessionAttrs(Map sessionAttrs) {        this.sessiOnAttrs= sessionAttrs;
   }    
   // redis 会自动销毁 session ,所以不需要使用下面的方法
   @JsonIgnore
   @Override
   public long getCreationTime() {        
       return 0;
   }    
   @JsonIgnore
   @Override
   public void setLastAccessedTime(long lastAccessedTime) {
   }    
   @JsonIgnore
   @Override
   public long getLastAccessedTime() {        
       return 0;
   }    
   @JsonIgnore
   @Override
   public void setMaxInactiveIntervalInSeconds(int interval) {
   }    
   @JsonIgnore
   @Override
   public int getMaxInactiveIntervalInSeconds() {        
       return 0;
   }    
   @JsonIgnore
   @Override
   public boolean isExpired() {        
       return false;
   }
}


七、实现SessionRepository接口会话持久层

这个类主要就是通过RedisTemplate 这个类对session对象的保存、修改、删除等操作

package com.itunion.config.session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.session.ExpiringSession;
import org.springframework.session.SessionRepository;
import java.util.concurrent.TimeUnit;
/**
* 主要用来管理session对象
*/

public
class WxRedisSessionRepository implements SessionRepository {
   private static Logger log = LoggerFactory.getLogger(WxRedisSessionRepository.class);    
   // redis 连接工具
   private RedisTemplate redisTemplate;    
   /**
    * 如果不为空,将覆盖默认的超时时间,单位秒
    * {@link ExpiringSession#setMaxInactiveIntervalInSeconds(int)}.
    */

   private Integer defaultMaxInactiveInterval;    
   public WxRedisSessionRepository(RedisTemplate redisTemplate) {        
       this.redisTemplate = redisTemplate;
   }    
   public WxRedisSessionRepository(RedisTemplate redisTemplate, Integer defaultMaxInactiveInterval) {        
       this.redisTemplate = redisTemplate;        
       this.defaultMaxInactiveInterval = defaultMaxInactiveInterval;
   }
   @Override    
   public WxRedisSession createSession()
{
       WxRedisSession session = new WxRedisSession();        
       log.debug("createSession " + session.getId());        
       return session;
   }
   @Override    
   public void save(WxRedisSession session)
{        
       log.debug("save " + session.getId());
       redisTemplate.opsForValue().set(session.getId(), session, defaultMaxInactiveInterval, TimeUnit.SECONDS);
   }
   @Override    
   public WxRedisSession getSession(String id)
{        
       log.debug("getSession " + id);        
       if (redisTemplate.hasKey(id)) {            
           return (WxRedisSession) redisTemplate.opsForValue().get(id);
       } else {            
           return null;
       }
   }
   @Override    
   public void delete(String id)
{        
       log.debug("delete " + id);
       redisTemplate.delete(id);
   }    
   public void setDefaultMaxInactiveInterval(Integer defaultMaxInactiveInterval) {        
       this.defaultMaxInactiveInterval = defaultMaxInactiveInterval;
   }
}


八、自定义会话策略 HttpSessionStrategy

这个类可以理解为一个请求过来了,程序从哪里去拿我需要的会话编号,主要用到的方法就是 getRequestedSessionId

package com.itunion.config.session;
import org.springframework.session.Session;
import org.springframework.session.web.http.HttpSessionStrategy;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
// 会话策略, 比如会话的标识从哪里获取
public
class WxHttpSessionStrategy implements HttpSessionStrategy {      private String name;    
       public WxHttpSessionStrategy() {        
       this("token");
   }    
   public WxHttpSessionStrategy(String name) {        
       this.name = name;
   }    
   @Override
   public String getRequestedSessionId(HttpServletRequest request) {        // 从header 中获取
       String token = request.getHeader(name);        
       if (token != null) return token;        
       // 从请求参数中获取
       token = request.getParameter(name);        
       if (token != null) return token;        
       // 增加自己的获取方式 比如:COOKIE
       return null;
   }    
   @Override
   public void onNewSession(Session session, HttpServletRequest request, HttpServletResponse response) {
       response.setHeader(this.name, session.getId());
   }    
   @Override
   public void onInvalidateSession(HttpServletRequest request, HttpServletResponse response) {
       response.setHeader(this.name, "");
   }    
   public void setName(String name) {        
       this.name = name;
   }
}


九、Redis 配置

这里我重新设置 StringRedisTemplate 值的序列化方式,把value内容序列化为json字符串
如果你希望只保存字符串的内容,可以只返回StringRedisTemplate对象

package com.itunion.config;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
@Configurationpublic class RedisConfig {    
   @Value("${spring.redis.host}")    
   private String host;    
   @Value("${spring.redis.port}")    
   private Integer port;    
   @Value("${spring.redis.password}")    
   private String password;    
   @Value("${spring.redis.database}")    
   private Integer database;    @Bean
   RedisTemplate redisTemplate(RedisConnectionFactory connectionFactory) {
       RedisTemplate redisTemplate = new StringRedisTemplate(connectionFactory);        
       // 重新设置 StringRedisTemplate 值的序列化方式,把value内容序列化为json字符串
       // 如果你希望只保存字符串的内容,可以吧下面的内容去掉只用StringRedisTemplate
       Jackson2JsonRedisSerializer redisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
       ObjectMapper om = new ObjectMapper();
       om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
       om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
       redisSerializer.setObjectMapper(om);
       redisTemplate.setValueSerializer(redisSerializer);        
       // 应用设置
       redisTemplate.afterPropertiesSet();        
       return redisTemplate;
   }    
   @Bean
   RedisConnectionFactory connectionFactory() {        
   // 建立redis 连接
       JedisConnectionFactory factory = new JedisConnectionFactory();
       factory.setHostName(host);
       factory.setPort(port);
       factory.setPassword(password);
       factory.setDatabase(database);        
       return factory;
   }
}


十、启用配置

这里需要使用 @EnableSpringHttpSession 注解

package com.itunion.config.session;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.session.config.annotation.web.http.EnableSpringHttpSession;
import org.springframework.session.web.http.HttpSessionStrategy;
@Configuration@EnableSpringHttpSessionpublic class HttpSessionConfig {    
   //session策略,这里默认会从头部,请求参数中获取内容
   // 这里的token 可以自定义,主要用于请求参数的名字
   @Bean
   HttpSessionStrategy httpSessionStrategy() {        
       return new WxHttpSessionStrategy("token");
   }    
   @Bean
   WxRedisSessionRepository sessionRepository(RedisTemplate redisTemplate) {        
       return new WxRedisSessionRepository(redisTemplate, 3600);
   }
}

启动Redis服务


启动项目

模拟移动端测试

  1. 模拟登录操作 http://localhost:8080/loginByWx?code=123

{
   "code":100,"message":null,"result":{"nickName":"Jim","loginBy":"weixin","token":"0eab2c62e185400489f51c060ed1360f"},"timestamp":1528954812490}

看下redis 的数据


  1. 模拟普通请求

token参数要取登录成功返回的token值
http://localhost:8080/hello?token=0eab2c62e185400489f51c060ed1360f

  1. 模拟退出
    http://localhost:8080/logout?token=0eab2c62e185400489f51c060ed1360f

redis 中对应的token也会被删除


总结

在本篇文章当中我们看到原先写的 HttpFilter 和 HttpServlet 在 Spring boot 中可以方便快捷的配置进来,对于我们老的项目的支持还是不错的


更多精彩内容

架构实战篇(一):Spring Boot 整合MyBatis

架构实战篇(二):Spring Boot 整合Swagger2

架构实战篇(三):Spring Boot 整合MyBatis()

架构实战篇(四):Spring Boot 整合 Thymeleaf

架构实战篇(五):Spring Boot 表单验证和异常处理

架构实战篇(六):Spring Boot RestTemplate的使用

架构实战篇(七):Spring Boot Data JPA 快速入门

架构实战篇(八):Spring Boot 集成 Druid 数据源监控


关注我们

Git源码地址:https://github.com/qiaohhgz/spring-boot-redis-session.git



推荐阅读
  • 本文介绍了使用kotlin实现动画效果的方法,包括上下移动、放大缩小、旋转等功能。通过代码示例演示了如何使用ObjectAnimator和AnimatorSet来实现动画效果,并提供了实现抖动效果的代码。同时还介绍了如何使用translationY和translationX来实现上下和左右移动的效果。最后还提供了一个anim_small.xml文件的代码示例,可以用来实现放大缩小的效果。 ... [详细]
  • 本文讨论了Alink回归预测的不完善问题,指出目前主要针对Python做案例,对其他语言支持不足。同时介绍了pom.xml文件的基本结构和使用方法,以及Maven的相关知识。最后,对Alink回归预测的未来发展提出了期待。 ... [详细]
  • 本文介绍了Android 7的学习笔记总结,包括最新的移动架构视频、大厂安卓面试真题和项目实战源码讲义。同时还分享了开源的完整内容,并提醒读者在使用FileProvider适配时要注意不同模块的AndroidManfiest.xml中配置的xml文件名必须不同,否则会出现问题。 ... [详细]
  • 在Xamarin XAML语言中如何在页面级别构建ControlTemplate控件模板
    本文介绍了在Xamarin XAML语言中如何在页面级别构建ControlTemplate控件模板的方法和步骤,包括将ResourceDictionary添加到页面中以及在ResourceDictionary中实现模板的构建。通过本文的阅读,读者可以了解到在Xamarin XAML语言中构建控件模板的具体操作步骤和语法形式。 ... [详细]
  • eclipse学习(第三章:ssh中的Hibernate)——11.Hibernate的缓存(2级缓存,get和load)
    本文介绍了eclipse学习中的第三章内容,主要讲解了ssh中的Hibernate的缓存,包括2级缓存和get方法、load方法的区别。文章还涉及了项目实践和相关知识点的讲解。 ... [详细]
  • ZSI.generate.Wsdl2PythonError: unsupported local simpleType restriction ... [详细]
  • XML介绍与使用的概述及标签规则
    本文介绍了XML的基本概念和用途,包括XML的可扩展性和标签的自定义特性。同时还详细解释了XML标签的规则,包括标签的尖括号和合法标识符的组成,标签必须成对出现的原则以及特殊标签的使用方法。通过本文的阅读,读者可以对XML的基本知识有一个全面的了解。 ... [详细]
  • Android系统移植与调试之如何修改Android设备状态条上音量加减键在横竖屏切换的时候的显示于隐藏
    本文介绍了如何修改Android设备状态条上音量加减键在横竖屏切换时的显示与隐藏。通过修改系统文件system_bar.xml实现了该功能,并分享了解决思路和经验。 ... [详细]
  • flowable工作流 流程变量_信也科技工作流平台的技术实践
    1背景随着公司业务发展及内部业务流程诉求的增长,目前信息化系统不能够很好满足期望,主要体现如下:目前OA流程引擎无法满足企业特定业务流程需求,且移动端体 ... [详细]
  • MyBatis多表查询与动态SQL使用
    本文介绍了MyBatis多表查询与动态SQL的使用方法,包括一对一查询和一对多查询。同时还介绍了动态SQL的使用,包括if标签、trim标签、where标签、set标签和foreach标签的用法。文章还提供了相关的配置信息和示例代码。 ... [详细]
  • 网络请求模块选择——axios框架的基本使用和封装
    本文介绍了选择网络请求模块axios的原因,以及axios框架的基本使用和封装方法。包括发送并发请求的演示,全局配置的设置,创建axios实例的方法,拦截器的使用,以及如何封装和请求响应劫持等内容。 ... [详细]
  • iOS超签签名服务器搭建及其优劣势
    本文介绍了搭建iOS超签签名服务器的原因和优势,包括不掉签、用户可以直接安装不需要信任、体验好等。同时也提到了超签的劣势,即一个证书只能安装100个,成本较高。文章还详细介绍了超签的实现原理,包括用户请求服务器安装mobileconfig文件、服务器调用苹果接口添加udid等步骤。最后,还提到了生成mobileconfig文件和导出AppleWorldwideDeveloperRelationsCertificationAuthority证书的方法。 ... [详细]
  • 本文介绍了在git中如何对指定的commit id打标签,并解决了忘记打标签的问题。通过查找历史提交的commit id,可以在任意时间点打上标签。同时,还介绍了git中的一些常用命令和操作。 ... [详细]
  • 单点登录原理及实现方案详解
    本文详细介绍了单点登录的原理及实现方案,其中包括共享Session的方式,以及基于Redis的Session共享方案。同时,还分享了作者在应用环境中所遇到的问题和经验,希望对读者有所帮助。 ... [详细]
  • Oracle seg,V$TEMPSEG_USAGE与Oracle排序的关系及使用方法
    本文介绍了Oracle seg,V$TEMPSEG_USAGE与Oracle排序之间的关系,V$TEMPSEG_USAGE是V_$SORT_USAGE的同义词,通过查询dba_objects和dba_synonyms视图可以了解到它们的详细信息。同时,还探讨了V$TEMPSEG_USAGE的使用方法。 ... [详细]
author-avatar
欧阳3721_208
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有