且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用Spring Boot,Session和Redis创建会话时未复制会话

更新时间:2022-01-29 00:09:56

感谢shobull将我指向

Thanks to shobull for pointing me to Justin Taylor's answer to this problem. For completeness, I wanted to put the full answer here too. It's a two part solution:

  1. 使Spring Session积极提交-自spring-session v1.0起,就有注释属性@EnableRedisHttpSession(redisFlushMode = RedisFlushMode.IMMEDIATE),可将会话数据立即保存到Redis中.文档此处.
  2. 简单的Zuul过滤器,用于将会话添加到当前请求的标头中:

  1. Make Spring Session commit eagerly - since spring-session v1.0 there is annotation property @EnableRedisHttpSession(redisFlushMode = RedisFlushMode.IMMEDIATE) which saves session data into Redis immediately. Documentation here.
  2. Simple Zuul filter for adding session into current request's header:

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import javax.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.session.Session;
import org.springframework.session.SessionRepository;
import org.springframework.stereotype.Component;

@Component
public class SessionSavingZuulPreFilter extends ZuulFilter {
    @Autowired
    private SessionRepository repository;

    private static final Logger log = LoggerFactory.getLogger(SessionSavingZuulPreFilter.class);

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 1;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
        RequestContext context = RequestContext.getCurrentContext();

        HttpSession httpSession = context.getRequest().getSession();
        Session session = repository.getSession(httpSession.getId());

        context.addZuulRequestHeader("Cookie", "SESSION=" + httpSession.getId());

        log.trace("ZuulPreFilter session proxy: {}", session.getId());

        return null;
    }
}

这两个都应该在您的Zuul代理中.

Both of these should be within your Zuul Proxy.