Spring Cloud Gateway中session共享

Spring Cloud Gateway中session共享

背景

在进行zuul切换到gateway时,需要重新实现session共享,本文主要分享一下自己实现的方案。

zuul中的session共享

在zuul中,是通过spring-session-data-redis这个组件,将session的信息存放到redis中实现的session共享。这次也简单说明下如何实现以及一些注意的点。

首先在网关zuul以及所有的微服务中添加spring-session-data-redis依赖:

<!-- session共享 -->
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
  <groupId>org.springframework.session</groupId>
  <artifactId>spring-session-data-redis</artifactId>
</dependency>

之后添加redis配置信息:

spring:
  redis:
    host: localhost
    port: 6379

添加EnableRedisHttpSession注解:

/**
 * 指定flushMode为IMMEDIATE 表示立即将session写入redis
 *
 * @author yuanzhihao
 * @since 2022/5/8
 */
@EnableRedisHttpSession(flushMode = FlushMode.IMMEDIATE)
@Configuration
public class RedisSessionConfig {
}

在网关zuul工程中,路由跳转到微服务时,需要添加sensitiveHeaders,设置为空,表示将敏感信息透传到下游微服务,这边需要将cookie的信息传下去,session共享保存到redis里面需要用到:

zuul:
  routes:
    portal:
      path: /portal/**
      sensitiveHeaders: # 将敏感信息传到下游服务
      serviceId: portal

指定server.servlet.context-path路径:

server.servlet.context-path=/gateway

zuul测试工程

在我的代码库中,我提交了一个简单的demo,主要有四个工程,分别是网关zuul、主页portal、两个客户端client-1、server-1。

网关zuul中添加路由信息:

spring:
  application:
    name: zuul
  redis:
    host: localhost
    port: 6379
server:
  servlet:
    context-path: /gateway
zuul:
  routes:
    portal:
      path: /portal/**
      sensitiveHeaders:
      serviceId: portal
    client-1:
      path: /client1/**
      sensitiveHeaders:
      serviceId: eureka-client1
    server-1:
      path: /server1/**
      sensitiveHeaders:
      serviceId: eureka-server1

添加登录过滤器,对所有的请求进行拦截,对于没有登录的请求会自动跳转到登录页面:

/**
 * 登录过滤器
 *
 * @author yuanzhihao
 * @since 2022/5/8
 */
@Component
@Slf4j
public class LoginFilter extends ZuulFilter {
    private static final List<String> white_List = Arrays.asList("/login", "/logout
  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值