CS/Network

세션 클러스터링

prden 2024. 9. 15. 14:53

1. 세션 클러스터링

 

Session clustering in the Spring Framework allows session data to be shared and synchronized across multiple application server instances in a clustered environment. This ensures that a user’s session is maintained regardless of which server in the cluster handles their request, enabling session failover and load balancing.

 

Why Use Session Clustering?

 

In a distributed system, requests from the same user may be routed to different servers. Without session clustering, if a user’s session is stored in memory on one server, and the next request goes to another server, the session data would be lost. To solve this, session clustering ensures that session data is shared across all servers.

 

How Session Clustering Works

 

In Spring, you can implement session clustering using external storage to share session data between nodes, ensuring that user sessions are available regardless of the node that handles the request.

 

Here are a few common approaches to session clustering in the Spring Framework:

 

1. Using an External Session Store (e.g., Redis, Hazelcast)

2. Using Spring Session (Redis or JDBC Store)

3. Tomcat/Jetty Session Replication

 

I’ll focus on Spring Session with Redis, which is a popular solution for session clustering in Spring Boot applications.

 

Example: Spring Session Clustering with Redis

 

Redis is an in-memory key-value store that is commonly used for sharing session data across a cluster of servers.

 

Step-by-Step Implementation of Session Clustering Using Redis in Spring Boot:

 

1. Add Dependencies

 

To use Spring Session with Redis, you’ll need to add the following dependencies to your pom.xml:

<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>

 

2. Configure Redis

 

In your application.properties or application.yml, configure Redis as the session store.

 

For application.properties:

# Redis configuration
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.password=your_redis_password

# Session configuration
spring.session.store-type=redis
spring.session.timeout=1800s  # Session timeout (30 minutes)

spring:
  redis:
    host: localhost
    port: 6379
    password: your_redis_password

  session:
    store-type: redis
    timeout: 1800s  # 30 minutes session timeout

 

In your main Spring Boot application class, you can enable Redis-backed session management by adding the @EnableRedisHttpSession annotation:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;

@SpringBootApplication
@EnableRedisHttpSession
public class SessionClusteringApplication {
    public static void main(String[] args) {
        SpringApplication.run(SessionClusteringApplication.class, args);
    }
}

 

his annotation automatically configures Redis as the session store.

 

4. Optional: Configure Redis Connection Factory

 

You may also define a custom Redis connection factory in a configuration class, which allows you to control aspects like connection pool size or timeout.

 

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;

@Configuration
public class RedisConfig {
    
    @Bean
    public RedisConnectionFactory redisConnectionFactory() {
        // You can configure Redis connection properties here
        return new LettuceConnectionFactory("localhost", 6379);
    }
}

 

5. Handling Sessions in Controllers

 

Spring automatically handles session management for you. For example, you can store and retrieve session attributes in your controllers as usual:

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

@RestController
public class SessionController {
    
    @GetMapping("/session")
    public String sessionExample(HttpSession session) {
        session.setAttribute("name", "John Doe");
        return "Session ID: " + session.getId() + " | Name: " + session.getAttribute("name");
    }
}

 

When requests hit different nodes in the cluster, Spring will still retrieve the session data from Redis, ensuring that the session remains consistent across all nodes.

 

6. Start Multiple Application Instances

 

Now you can start multiple instances of your Spring Boot application, and all of them will share session data using Redis.

 

You can start your application with different ports like this:

# Start the first instance on port 8080
java -jar -Dserver.port=8080 session-clustering.jar

# Start the second instance on port 8081
java -jar -Dserver.port=8081 session-clustering.jar

 

7. Test the Session Clustering

 

Access the first instance at http://localhost:8080/session. This will create a session and store the session ID in Redis.

Then, access the second instance at http://localhost:8081/session. You should still see the session data retrieved from Redis, even though you hit a different server instance.

 

How Spring Session with Redis Works

 

Session Storage in Redis: When a user logs in or interacts with the system, their session data is saved in Redis. This is achieved through a key-value pair, where the key is the session ID and the value is the session data.

Session Synchronization: Each time a new request comes in, the session ID is sent in the HTTP request (usually via cookies). The server retrieves the session data from Redis, regardless of which node in the cluster the request goes to. This allows all instances in the cluster to have a consistent view of the user’s session.

Failover: If one server fails, the user’s session is not lost because it’s stored in Redis. The user’s session will continue to work on other nodes in the cluster.

 

Alternative Methods for Session Clustering

 

1. Hazelcast: Hazelcast is another in-memory data grid used for sharing session data across a cluster.

You can use Spring Session with Hazelcast as an alternative to Redis.

Similar setup to Redis, just different dependencies and configuration.

2. JDBC-Based Session Storage: Instead of Redis, you can store sessions in a relational database using Spring Session with JDBC. The sessions are stored in a database, and each server in the cluster can access the same session data.

3. Tomcat Session Replication: If you’re using Tomcat as the servlet container, it has built-in support for session replication. You can configure Tomcat to replicate sessions across all nodes in the cluster using multicast or a dedicated session manager.

 

Advantages of Spring Session Clustering with Redis

 

Scalability: Redis is extremely fast and scalable. It handles session storage with high throughput, which is ideal for applications that need to scale horizontally across many nodes.

Fault Tolerance: By using Redis as a distributed session store, user sessions are not lost when a server fails.

Stateless Servers: With Redis handling session data, your servers become stateless, which simplifies scaling and reduces server resource usage.

 

Conclusion

 

Session clustering in the Spring Framework can be easily achieved using Spring Session with Redis, allowing multiple application instances to share session data. This approach helps ensure that user sessions are consistent, even when requests are routed to different servers in a clustered environment. The Redis-backed session store is a common solution due to its speed and scalability, but alternatives like Hazelcast or JDBC can also be used depending on your application’s needs.


https://kku-jun.tistory.com/44

 

세션 클러스터링이란?

세션 클러스터링이란? 세션 클러스터링이란 WAS가 2대 이상 설치가 되어있을 경우 세션을 공유하여 대체된 WAS에도 동일한 세션을 관리하는 것을 의미합니다. 예를 들어 L4 스위치가 사용자를 접

kku-jun.tistory.com

 

 

 

https://junshock5.tistory.com/91

 

세션 클러스터링 이란?

세션 클러스터링 이란? 두 대 이상의 WAS를 이용하는 경우 로드 밸런싱(대용량 트래픽 처리시 분산시키는 것), 또는 failover(장애 발생시 예비시스템으로 자동전환, 서버 이중화), auto scaling(AWS에서

junshock5.tistory.com

2. JBoss Infinispan

https://jsonobject.tistory.com/441

 

Spring Boot, JBoss Infinispan을 이용한 분산 캐시 적용하기

개요 마이크로서비스의 유행과 함께 NoSQL 저장소의 사용이 필수인 시대가 되었다. 이제는 전통적인 RDBMS 저장소 만으로는 복잡한 비즈니스 로직과 병렬적인 빠른 동시성 처리 요구를 수용하기

jsonobject.tistory.com

 

3. 로그인 인증방식 Session VS. JWT