热门标签 | 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



推荐阅读
  • 基于PgpoolII的PostgreSQL集群安装与配置教程
    本文介绍了基于PgpoolII的PostgreSQL集群的安装与配置教程。Pgpool-II是一个位于PostgreSQL服务器和PostgreSQL数据库客户端之间的中间件,提供了连接池、复制、负载均衡、缓存、看门狗、限制链接等功能,可以用于搭建高可用的PostgreSQL集群。文章详细介绍了通过yum安装Pgpool-II的步骤,并提供了相关的官方参考地址。 ... [详细]
  • 云原生边缘计算之KubeEdge简介及功能特点
    本文介绍了云原生边缘计算中的KubeEdge系统,该系统是一个开源系统,用于将容器化应用程序编排功能扩展到Edge的主机。它基于Kubernetes构建,并为网络应用程序提供基础架构支持。同时,KubeEdge具有离线模式、基于Kubernetes的节点、群集、应用程序和设备管理、资源优化等特点。此外,KubeEdge还支持跨平台工作,在私有、公共和混合云中都可以运行。同时,KubeEdge还提供数据管理和数据分析管道引擎的支持。最后,本文还介绍了KubeEdge系统生成证书的方法。 ... [详细]
  • 本文介绍了Java工具类库Hutool,该工具包封装了对文件、流、加密解密、转码、正则、线程、XML等JDK方法的封装,并提供了各种Util工具类。同时,还介绍了Hutool的组件,包括动态代理、布隆过滤、缓存、定时任务等功能。该工具包可以简化Java代码,提高开发效率。 ... [详细]
  • android listview OnItemClickListener失效原因
    最近在做listview时发现OnItemClickListener失效的问题,经过查找发现是因为button的原因。不仅listitem中存在button会影响OnItemClickListener事件的失效,还会导致单击后listview每个item的背景改变,使得item中的所有有关焦点的事件都失效。本文给出了一个范例来说明这种情况,并提供了解决方法。 ... [详细]
  • CF:3D City Model(小思维)问题解析和代码实现
    本文通过解析CF:3D City Model问题,介绍了问题的背景和要求,并给出了相应的代码实现。该问题涉及到在一个矩形的网格上建造城市的情景,每个网格单元可以作为建筑的基础,建筑由多个立方体叠加而成。文章详细讲解了问题的解决思路,并给出了相应的代码实现供读者参考。 ... [详细]
  • 本文介绍了Android 7的学习笔记总结,包括最新的移动架构视频、大厂安卓面试真题和项目实战源码讲义。同时还分享了开源的完整内容,并提醒读者在使用FileProvider适配时要注意不同模块的AndroidManfiest.xml中配置的xml文件名必须不同,否则会出现问题。 ... [详细]
  • 本文分享了一个关于在C#中使用异步代码的问题,作者在控制台中运行时代码正常工作,但在Windows窗体中却无法正常工作。作者尝试搜索局域网上的主机,但在窗体中计数器没有减少。文章提供了相关的代码和解决思路。 ... [详细]
  • 目录实现效果:实现环境实现方法一:基本思路主要代码JavaScript代码总结方法二主要代码总结方法三基本思路主要代码JavaScriptHTML总结实 ... [详细]
  • Android中高级面试必知必会,积累总结
    本文介绍了Android中高级面试的必知必会内容,并总结了相关经验。文章指出,如今的Android市场对开发人员的要求更高,需要更专业的人才。同时,文章还给出了针对Android岗位的职责和要求,并提供了简历突出的建议。 ... [详细]
  • Centos7.6安装Gitlab教程及注意事项
    本文介绍了在Centos7.6系统下安装Gitlab的详细教程,并提供了一些注意事项。教程包括查看系统版本、安装必要的软件包、配置防火墙等步骤。同时,还强调了使用阿里云服务器时的特殊配置需求,以及建议至少4GB的可用RAM来运行GitLab。 ... [详细]
  • Metasploit攻击渗透实践
    本文介绍了Metasploit攻击渗透实践的内容和要求,包括主动攻击、针对浏览器和客户端的攻击,以及成功应用辅助模块的实践过程。其中涉及使用Hydra在不知道密码的情况下攻击metsploit2靶机获取密码,以及攻击浏览器中的tomcat服务的具体步骤。同时还讲解了爆破密码的方法和设置攻击目标主机的相关参数。 ... [详细]
  • baresip android编译、运行教程1语音通话
    本文介绍了如何在安卓平台上编译和运行baresip android,包括下载相关的sdk和ndk,修改ndk路径和输出目录,以及创建一个c++的安卓工程并将目录考到cpp下。详细步骤可参考给出的链接和文档。 ... [详细]
  • 使用在线工具jsonschema2pojo根据json生成java对象
    本文介绍了使用在线工具jsonschema2pojo根据json生成java对象的方法。通过该工具,用户只需将json字符串复制到输入框中,即可自动将其转换成java对象。该工具还能解析列表式的json数据,并将嵌套在内层的对象也解析出来。本文以请求github的api为例,展示了使用该工具的步骤和效果。 ... [详细]
  • 单点登录原理及实现方案详解
    本文详细介绍了单点登录的原理及实现方案,其中包括共享Session的方式,以及基于Redis的Session共享方案。同时,还分享了作者在应用环境中所遇到的问题和经验,希望对读者有所帮助。 ... [详细]
  • mysql-cluster集群sql节点高可用keepalived的故障处理过程
    本文描述了mysql-cluster集群sql节点高可用keepalived的故障处理过程,包括故障发生时间、故障描述、故障分析等内容。根据keepalived的日志分析,发现bogus VRRP packet received on eth0 !!!等错误信息,进而导致vip地址失效,使得mysql-cluster的api无法访问。针对这个问题,本文提供了相应的解决方案。 ... [详细]
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社区 版权所有