cloud微服务之间的调用session共享失效

33 篇文章 1 订阅
2 篇文章 1 订阅

在微服务开发中,如何让多个微服务之间的session共享,如:登录的账号或其他信息需要保存到session中,但是不使用全局session肯定其他的微服务不能调用

我们的目的:让微服务A保存的sesion在微服务B中也能获取

因为我这里集成了OpenFein,在服务A使用OpenFein调用服务B时发现无法获取session,但是单独去执行服务B方法时又可以获取了,这是因为在连接调用时出现的问题?

第一步:这里以微服务A ,微服务B为案例

两个微服务的pom.xml类必须加入依赖

  <!--加载 springboot redis包  -->
		<dependency>
		  <groupId>org.springframework.boot</groupId>
		  <artifactId>spring-boot-starter-data-redis</artifactId>
		</dependency>
		<!-- redis session全局共享 -->
		<dependency>  
		        <groupId>org.springframework.session</groupId>  
		        <artifactId>spring-session-data-redis</artifactId>  
		</dependency>

第二步:两个微服务的yml文件均连接redis

#springboot集成redis
  redis:
    host: localhost
    port: 6379

第三步:两个微服务的主启动类均加上

@EnableRedisHttpSession//session共享

到这一步:单独访问两个服务获取session没问题,但是一个调用一个再获取就不行了

如何处理?

我们只需要写一个类继承RequestInterceptor 实现其中的方法,传递session信息即可

mport javax.servlet.http.HttpServletRequest;

import org.springframework.session.web.http.SessionRepositoryFilter;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import feign.RequestInterceptor;

/**
 * feign调用时传递session信息
 * @date 2018/12/7 16:39
 */
@Component
public class FeignRequestIntercepter implements RequestInterceptor {

	@Override
	public void apply(feign.RequestTemplate requestTemplate) {
		 //通过RequestContextHolder获取本地请求
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if (requestAttributes == null) {
            return;
        }
        //获取本地线程绑定的请求对象
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        //给请求模板附加本地线程头部信息,主要是cookie信息
        Enumeration headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String name = headerNames.nextElement().toString();
            requestTemplate.header(name, request.getHeader(name));
        }
        if(!request.isRequestedSessionIdValid()){
            request.setAttribute(SessionRepositoryFilter.INVALID_SESSION_ID_ATTR,null);
            requestTemplate.header("cookie","SESSION="+request.getSession().getId());
        }
		
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

hexu_blog

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值