练习 - 在 Redis 中存储 HTTP 会话数据

已完成

在本单元中,向现有 Spring Boot 应用程序添加 Spring Session,以在 Azure Cache for Redis 中存储 HTTP 会话数据。

配置 Spring Session

  1. 要向应用程序添加 Spring Session 支持,请在 pom.xml 文件的 <dependencies> 部分中添加以下依赖项:

    <dependency>
        <groupId>org.springframework.session</groupId>
        <artifactId>spring-session-data-redis</artifactId>
    </dependency>
    
  2. 要将 Spring Session 配置为使用 Redis 进行会话复制,请将以下行添加到 src/main/resources/application.properties 文件中:

    spring.session.store-type=redis
    

添加新控制器以测试会话复制

向应用程序添加新的 Spring MVC REST 控制器,用于测试会话复制。

  1. 在 TodoController 旁边创建一个名为 SessionReplicationController 的新控制器。

    package com.example.demo;
    
    import org.springframework.context.annotation.Bean;
    import org.springframework.session.data.redis.config.ConfigureRedisAction;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    import javax.servlet.http.HttpSession;
    
    @RestController
    @RequestMapping("/")
    public class SessionReplicationController {
    
        @Bean
        public static ConfigureRedisAction configureRedisAction() {
            return ConfigureRedisAction.NO_OP;
        }
    
        @GetMapping("/session")
        public String session(HttpSession session) {
            Integer test = (Integer) session.getAttribute("test");
            if (test == null) {
                test = 0;
            } else {
                test++;
            }
            session.setAttribute("test", test);
            return "[" + session.getId() + "]-" + test;
        }
    }
    

    注意

    配置一个特定的 ConfigureRedisAction.NO_OP Spring bean,因为默认情况下,Spring Session 会尝试设置 Redis 密钥空间通知,该设置对受保护的 Azure Cache for Redis 实例不起作用。 如果需要针对 Azure Cache for Redis 的密钥空间通知,则必须通过 Redis CLI 手动应用它们。

    密钥空间通知对 WebSocket 很有用,但它们会消耗更多资源。 当前方案不使用 WebSocket,不应启用密钥空间通知。

  2. 重启应用程序以受益于 HTTP 会话复制。

测试会话复制

HTTP 会话特定于用户,并通过 cookie 进行维护。 可以使用以下任一方法来测试会话是否正常工作:

  • 将浏览器指向 http://localhost:8080/session 并多次重新加载页面。

  • 多次运行以下命令行:

    curl -b cookie.txt -c cookie.txt http://127.0.0.1:8080/session
    

    上述命令将 Cookie 保存在名为 cookie.txt 的文件中。

这两种方法都会生成显示 HTTP 会话 ID 的输出,其中包含一个在每次请求后递增的数字,如以下示例所示:

Screenshot that shows example output for session replication.

要检查是否已正确保留会话,请重启服务器,并验证会话数据是否未丢失。

在下一单元中,将应用程序部署到云,并在本地计算机与云服务之间聚集 HTTP 会话。