SpringSession etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster
SpringSession etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster

22 Şubat 2023 Çarşamba

SpringSession Mongo

Maven
Şu satırı dahil ederiz
<dependency>
   <groupId>org.springframework.session</groupId>
   <artifactId>spring-session-core</artifactId>
</dependency>
<dependency>
   <groupId>org.springframework.session</groupId>
   <artifactId>spring-session-data-mongodb</artifactId>
</dependency>
application.properties
Örnek
Şöyle yaparız
spring.data.mongodb.database=sessionDb
spring.data.mongodb.port=27017
spring.data.mongodb.host=localhost 
spring.data.mongodb.authentication-database=admin
spring.data.mongodb.username=admin
spring.data.mongodb.password=password



11 Ocak 2023 Çarşamba

SpringSession Redis

Giriş
Açıklaması şöyle
How does this work?
1. We inform Spring that sessions will now be cached in Redis.
2. Spring receives a request.
3. Spring Security kicks in and user is authenticated.
4. Spring Session object is serialized and saved in the cache.
5. Client gets a cookie with the Session ID.
6. Client then sends the session id for further requests.
7. Any instance of the UI Service will check in the cache for a session object against the Session ID provided by the client.
8. Session object is de-serialized and reused.
Gradle
Şöyle yaparız
dependencies {
  compile 'org.springframework.boot:spring-boot-starter-data-redis'
  compile("org.springframework.boot:spring-boot-starter-cache")
  implementation('org.springframework.session:spring-session-data-redis')
}
1. @EnableRedisHttpSession Anotasyonu
Açıklaması şöyle
This annotation when parsed, creates a Spring Bean with the name of springSessionRepositoryFilter that implements Filter. The filter is in charge of replacing the HttpSession implementation to be backed by Spring Session. In this instance, Spring Session is backed by Redis.
Örnek
Şöyle yaparız
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;

@EnableRedisHttpSession
@EnableEurekaClient
@SpringBootApplication
public class UIApplication {

  public static void main(String[] args) {
    SpringApplication.run(UIApplication.class, args);
  }
}
2. application.properties
Şöyle yaparız
spring.cache.type=redis
spring.redis.host=<ip-address>
spring.redis.port=<Redis port>



SpringSession Kullanımı

Giriş
Session bilgisinin Spring dışında başka bir yerde saklanması içindir. 
SpringSession ile kullanılabilecek şeyler şunlar

Nasıl Çalışır
Açıklaması şöyle
How does Centralized Sessions work in Spring?
A web server creates a HTTP Session for spring to work on and save authentication details and other user/request specific details. The server then send the Session ID back to the client in a cookie.

This works fine, if you have a single instance of an application. All hell breaks loose when microservices come into the picture. To mitigate this Spring came up with Spring Session.

Spring Session makes it trivial to support clustered sessions without being tied to an application container specific solution.

It replaces the HttpSession in an application container (i.e. Tomcat) in a neutral way, with support for providing session IDs in headers to work with RESTful APIs.

We need to save this session somewhere that is common to every instance. And that common place should be very fast to return back the details of the session.

So, we need a cache. But what kind? Database or In memory?

Both have their pros and cons. Database is cheaper on the storage but is slow. In-memory cache while fast will have to work with a limited amount of RAM.

If your concurrent users aren’t in the millions and you have decent enough servers then In-memory caching is the better solution here.
Açıklaması şöyle
But what is really under the hood and what is really happening when we are using session data mongo? In fact, the majority of this magic is being done by the SessionRepositoryFilter. If you track down the HTTP request and see where actually the session object is created you will notice multiple things:

The HttpServletRequest is wrapped by the SessionRepositoryFilter, which also overrides the methods for obtaining a HttpSession. SessionRepositoryFilter will check the validity of the token first and also:

- Will check if any cookie is present and will load the session data from the store
- Will convert the HttpSession into a MongoSession
- will update session data in the store

There are a lot of different dependencies available that you can use based on the store that you are using or are more comfortable with.
Yani SpringSession kullanıyorsak HttpSession veya HttpServletRequest kullanılsak bile aslında bu başka bir sınıf ile sarmalanmıştır

Örnek
Şöyle yaparız
@Slf4j
@Controller
public class TestController {

  @RequestMapping("mongodb-session")
  public String getSession(HttpSession session){
    if ( session.getAttribute("counter") == null ){
      session.setAttribute("counter" , 1 );
      log.info( "New user");
    } else {
      log.info( "visit count : " + session.getAttribute("counter")  );
      session.setAttribute("counter" , (int) session.getAttribute("counter") + 1 );
    }
    return "mongodb-session.html";
  }
}



23 Eylül 2021 Perşembe

SpringSession Apache Ignite

Maven
Şu satırı dahil ederiz. ignite-spring ve ignite-spring-data-2.2-ext SpringData kullanımı için lazım
<properties>
  <ignite.version>2.10.0</ignite.version>
  <ignite.spring.data.version>1.0.0</ignite.spring.data.version>
</properties>

<dependency>
  <groupId>org.apache.ignite</groupId>
  <artifactId>ignite-core</artifactId>
  <version>${ignite.version}</version>
</dependency>

<dependency>
  <groupId>org.apache.ignite</groupId>
  <artifactId>ignite-spring</artifactId>
  <version>${ignite.version}</version>
</dependency>

<dependency>
  <groupId>org.apache.ignite</groupId>
  <artifactId>ignite-spring-data-2.2-ext</artifactId>
  <version>${ignite.spring.data.version}</version>
</dependency>
Kullanım
IgniteClient bean'i yaratırız
//ignite.addresses: 127.0.0.1:10800

@Value("${ignite.addresses}")
private final List<String> addresses;

@Bean
public IgniteClient ignite() {
  ClientConfiguration cfg = new ClientConfiguration()
    .setAddresses(addresses.toArray(new String[0]));

  return Ignition.startClient(cfg);
}
1. IgniteRepository'den kalıtan kendi Repository bean'imizi yaratırız.
2. org.springframework.session.SessionRepository'den kalıtan kendi sınıfımızı yazarız. Ve Bu sınıf içinde IgniteRepository nesnesini kullanarak session bilgisini kaydederiz.


Örnek
Şöyle yaparız
@RepositoryConfig(cacheName = "SessionCache", igniteInstance = IGNITE_NAME,
  autoCreateCache = true)
public interface SessionRepository extends IgniteRepository<MapSession, String> {
}



SpringSession SessionRepository Arayüzü

Giriş
Şu satırı dahil ederiz
import org.springframework.session.SessionRepository;
Örnek
Şöyle yaparız
import org.springframework.session.MapSession; @Repository
@RequiredArgsConstructor
public class IgniteSessionRepository implements SessionRepository<MapSession> {
  private final SessionRepository sessionRepo;

  @Value("${sessions.maxInactiveInterval:1800}")
  private final long maxInactiveInterval;

  @Override
  public MapSession createSession() {
    MapSession session = new MapSession();

    session.setMaxInactiveInterval(Duration.ofMinutes(maxInactiveInterval));

    return session;
  }

  @Override
  public void save(MapSession session) {
    sessionRepo.save(session.getId(), session);
  }

  @Override
  public MapSession findById(String id) {
    return sessionRepo.findById(id).orElseThrow();
  }

  @Override
  public void deleteById(String id) {
    sessionRepo.deleteById(id);
  }
}

8 Aralık 2019 Pazar

SpringBoot spring.server Session Ayarları

Giriş
Embedded Tomcat kullanıyorsak bazı ayarları application.properties dosyasında tanımlamak mümkün.

Session bilgisi JDBC, Gemfire, MongoDB, Redis üzerinde saklanabilir.

persistent Alanı
Açıklaması şöyle. Sunucu tekrar başlasa bile tekrar login olması gerekmez.
Persistent session are opt-in; either by setting persistenSession on the ConfigurableEmbeddedServletContainer or by using the property server.session.persistent=true.
Örnek
Şöyle yaparız
server.servlet.session.persistent=true
timeout Alanı
Şöyle yaparız.
server.servlet.session.timeout=3m
store-type Alanı
Örnek
Eğer session saklamak istemezsek şöyle yaparız.
spring.session.store-type=none
server.servlet.session.timeout=-1
Örnek
Redis için şöyle yaparız.
spring.session.store-type=redis
# redis database
spring.redis.database=8
# redis host
spring.redis.host=102.128.2.65
# redis password
#spring.redis.password=
#redis port
spring.redis.port=6379
Örnek
Şöyle yaparız.
server:
  servlet:
    session:
      persistent: true
spring:
  session:
    store-type: redis
  redis:
    host: localhost
    port: 6379
 ...

10 Mayıs 2019 Cuma

SpringSession @EnableRedisHttpSession Anotasyonu

Giriş
Şu satırı dahil ederiz.
<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>
Hazelcast kullanmak istersk @EnableHazelcastHttpSession anotasyonunu kullanırız.
Örnek
Şöyle yaparız.
@Configuration
@EnableRedisHttpSession
public class RedisSessionConfig {
  @Bean
  public RedisTemplate<Object, Object> sessionRedisTemplate(
            RedisConnectionFactory connectionFactory) {
    RedisTemplate<Object, Object> template = new RedisTemplate<>();
    template.setKeySerializer(new GenericJackson2JsonRedisSerializer());
    template.setHashKeySerializer(new GenericJackson2JsonRedisSerializer());
    template.setConnectionFactory(connectionFactory);
    return template;
  }
}
Ayarlar için şöyle yaparız.
spring.session.store-type=redis
# redis database
spring.redis.database=8
# redis host
spring.redis.host=102.128.2.65
# redis password
#spring.redis.password=
#redis port
spring.redis.port=6379