会话保持是微服务绕不开的一个话题。
在spring cloud中采用redis保存session信息的方式来保持会话。
接下来我们在前面工程的基础上配置一下redis,实现会话保持。
首先看一下保持不了的会话是什么样。
在service1和service2中分别新建会话模块,创建ConversationController
service1 ConversationController
package com.hao1st.service1.biz.conversation.controller;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/c")
public class ConversationController {
    @GetMapping("/session")
    public String index(HttpServletRequest request) {
        HttpSession session = request.getSession();
        return "service1的会话ID为:" + session.getId();
    }
}service2 ConversationController
package com.hao1st.service2.biz.conversation.controller;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/c")
public class ConversationController {
    @GetMapping("/session")
    public String index(HttpServletRequest request) {
        HttpSession session = request.getSession();
        return "service2的会话ID为:" + session.getId();
    }
}依次启动eureka、gateway、service1、service2,并分别访问这两个controller,可以看到两次访问是不同的会话ID


可以看到,这俩session id不一样。
那就让他一样。
需要在microservices中添加如下依赖:
implementation 'org.springframework.boot:spring-boot-starter-data-redis'
implementation 'org.springframework.session:spring-session-data-redis'在两个service的application.yml中添加redis的配置,注意:redis需要自己提前准备好。
spring:
  application:
    name: service2
  data:
    redis:
      host: 127.0.0.1
      port: 6379
      password: 123456
      lettuce:
        pool:
          max-active: 8
          max-wait: -1ms
          max-idle: 8
          min-idle: 0
      database: 0spring.data下是redis配置,跟spring.application同级。
再次运行service1和service2,访问controller,id同了~











