11 Ocak 2023 Çarşamba

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";
  }
}



Hiç yorum yok:

Yorum Gönder