봄에 분산 세션 관리를 구현하십시오
이 기사는 주로 봄에 분산 세션을 구현하고 Redis를 사용하여 세션을 지속합니다. 이러한 방식으로, 응용 프로그램이 배포되면, 수지 및 Tomcat과 같은 컨테이너에 분산을 구성 할 필요가 없으므로 클러스터 확장을 위해 새 노드 서버를 추가하기에 편리합니다. 세션은 각 노드의 서버에 의존하지 않으며 Redis에서 직접 얻을 수 있습니다. 기능의 핵심 코드는 다음과 같습니다.
1. 먼저 web.xml에서 구성하십시오
인터셉터에 추가 :
<!-분산 세션 시작-> <filter> <filter-name> distributedSessionFilter </filter-name> <filter-class> distributedSessionFilter </filter-class> <init-param> <!-필수, 키. 2 가지 방법, 1은 Bean에 해당하고 형식은 Bean : Key입니다. 2 줄, affffrfgv-> <param-name> 키 </param-name> <param- value> xxxxxxxx </param- value> </init-param> <init-param> <!-필수, Redis에 해당하는 Bean : xx-> <param-name> cachebean </param-name> <Param-value> Bean : redispersistent </param-value> //이 인터페이스에 해당하는 분산베이스 interc <filter-name> distributedSessionFilter </filter-name> <Url-pattern>*
2. 인터셉터의 구현, 핵심 코드는 다음과 같습니다.
주로 다음 범주가 있습니다.
1. 분산 소재 필터는 필터를 구현합니다.
import java.io.ioexception; import java.util.hashmap; import java.util.map; import javax.servlet.filter; import javax.servlet.filterchain; import javax.servlet.filterconfig; import javax.servlet.servletexception; javax.servlet.servletresponse; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; import org.springframework.web.context.webapplicationcontext; 가져 오기 org.springframework.web.context.support.webapplicationcontextutils; public class distromedsessionfilter implements 필터 {private static final logger log = loggerfactory.getLogger (deptremedsessionfilter.class); 개인 문자열 Cookiename; // 주로 Session Private DistributessessionManager DistributedSessionManager를 관리하는 작업입니다. 개인 문자열 키;}컨테이너가 시작될 때 초기화 방법 :
@override public void init (FilterConfig Config) servleTeXception {webApplicationContext wac = webApplicationContextUtils.getRequiredWebApplicationContext (config .getServletContext ()); String key = config.getInitParameter ( "key"); 문자열 cookiename = config.getInitParameter ( "Cookiename"); String CacheBean = config.getInitParameter ( "CacheBean"); // Bean의 이름을 얻으면 구성은 "Bean :"String redisbeanstr = cachebean.substring (5); DistromedBaseInterface distributedCache = (분산베이스 interface) wac.getBean (redisbeanstr); // 키를 얻고, 2 개의 구성 메소드가 있고 1은 Bean에 해당하며 형식은 Bean : Key입니다. 2 문자열 if (key.startSwith ( "bean :")) {this.key = (string) wac.getBean (key.substring (5)); } else {this.key = 키; } this.cookiename = cookiename; this.distributedSessionManager = distributedSessionManager.getInstance (distributedCache); // 예외 처리는 생략됩니다. . . }실제 요청 차단 수행 :
@override public void dofilter (servletrequest servletrequest, servletresponse servletreponse, filterchain filterchain) throws servletexception, ioexception {distromedhttpervletrequestwrapper distreq = null; try {// processing processing distreq = created ProtipributeedRequest (servletrequest, servletresponse); filterchain.dofilter (distreq, servletresponse); } catch (Throwable e) {// 생략. . . } lANDE {if (distreq! = null) {try {// 요청을 처리 한 후 세션을 처리 한 후 (주로 세션 세션 저장) DeCESSESSEFTERREQUEST (ZILLEQ.GETSESSION ()); } catch (Throwable e2) {// 생략. . . }}}}} // 분산 요청 private private eptination httpervletRequestWrapper createPhriptedRequest (servletRequest servletRequest, servletResponse servletResponse)는 ioException, servLeteXception {httpservletRequest 요청 = (httpervletRequest) servletRequest; httpservletresponse 응답 = (httpservletResponse) servletResponse; String userID = cookieutil.getCookie (Cookiename, request); String allySid = distributedSessionManager.GetActualSid (userSID, request, key); if (stringUtil.isblank (realsid)) {if (stringUtil.isnotblank (usersId)) {log.info ( "userID [{}] verification fails", usersId); } // 쿠키 문자열 쓰기 [] userIdarr = distributedSessionManager.createUsersId (request, key); userId = userIdarr [0]; Cookieutil.SetCookie (Cookiename, UsersId, 요청, 응답); realSID = userIdarr [1]; } realysid = "sid :" + realsid; distributedhttpsessionwrapper distsession = null; try {map <string, object> allattribute = distromedsessionmanager.getSession (realsId, request.getSession () .getMaxInactiveInterVal ()); distsession = new distromepedhttpsessionWrapper (realSid, request.getSession (), allattribute); } catch (Throwable e) {// 오류가 발생하여 캐시 된 데이터 로그를 삭제합니다 (e.getMessage (), e); map <string, object> allattribute = new Hashmap <String, object> (); distsession = new distromepedhttpsessionWrapper (realSid, request.getSession (), allattribute); DistributedSessionManager.removesession (distsession); } emptipredHttPervletRequestWrapper requestWrapper = new epplicedHtTpservletRequestWrapper (요청, Distsession); 반환 요청 표시; } // Operation Session Private void DeCESSESSEFTERREQUEST (distributedHttPsessionWrapper Session) {if (session == null) {return; } if (session.changed) {distributedSessionManager.Savesession (세션); } else if (session.invalidated) {distributedSessionManager.RemoveSession (세션); } else {deptremedsessionmanager.expire (세션); }}2. DistributedSessionManager는 주로 분산 세션, 핵심 코드를 다루는다 :
Class DistributedSessionManager {보호 된 정적 최종 로저 로그 = loggerFactory.getLogger (DistributedSessionManager.class); Private STATIC DEPTEREDSESSIONMANAGER instance = NULL; // redis는 세션 인터페이스를 처리하고 개인 분산베이스 interface distretbaseinterface를 구현합니다. 개인 정적 바이트 [] lock = 새로운 바이트 [1]; Private DistributedSessionManager (DistributedBaseInterface distributedBaseInterface) {this.DistributedBaseInterface = DistromedBaseInterface; } public static districedsessionmanager getInstance (distributedBaseInterface redis) {if (instance == null) {synchronized (lock) {if (instance == null) {instance = new eppleedSessionManager (redis); }}} return 인스턴스; } // 세션 가져 오기 <문자열, 객체> getSession (String Sid, int Schoc if (stringUtil.isnotblank (json)) {return jsonutil.unserializemap (json); } return new Hashmap <String, Object> (1); } // 세션 저장 세션 저장 공개 void savesession (distributedhttpsessionWrapper session) {map <string, object> map = session.allattribute; if (maputil.isempty (map)) {return; } string json = jsonutil.serializemap (map); this.distributedBaseInterface.set (session.getId (), json, session.getMaxInactiveInterval ()); } // 세션 삭제 public void removeSession (distributedHttPsessionWrapper Session) {deptomedBaseInterface.del (session.getId ()); } public void expire (distributedHttPsessionWrapper Session) {deptationBaseInterface.expire (session.getId (), session.getMaxInactiveInterVal ()); } /** * 쿠키의 sid 만들기 * /public string [] createUsersId (httpservletRequest 요청, 문자열 키) {// ...} public String getActualSid (String UsersId, httpservletRequest 요청, 문자열 키) {// ...}}3. DistributedHtTpsessionWrapper는 httpsession을 구현하고 분산 세션 포장, 핵심 코드를 수행합니다.
공개 클래스 분산 httpsessionWrapper는 httpsession {private httpsession orgisession; 개인 문자열 sid; 부울 변경 = 거짓; 부울 무효화 = 거짓; 지도 <문자열, 객체> allattribute; public distributedhttpsessionWrapper (String Sid, httpsession Session, Map <String, Object> AllAttribute) {this.orgisession = session; this.sid = sid; this.allattribute = allattribute; } @override public String getId () {return this.sid; } @override public void stattribute (문자열 이름, 개체 값) {change = true; Allattribute.put (이름, 값); } @override public object getAttribute (문자열 이름) {return allattribute.get (name); } @override public enumeration <string> getAttributeNames () {set <string> set = allattribute.keyset (); iterator <string> iterator = set.iterator (); 새로운 myEnumeration <String> (ITERATOR)을 반환합니다. } 개인 클래스 myEenumeration <t> 열거 <t> {iterator <t> iterator; public myEenumeration (iterator <t> iterator) {super (); this.iterator = iterator; } @override public boolean hasmoreElements () {return iterator.hasnext (); } @override public t NextElement () {return iterator.next (); }} @override public void invalidate () {this.invalidated = true; } @override public void removeattribute (문자열 이름) {change = true; Allattribute.remove (이름); } @override public long getCreationTime () {return orgisession.getCreationTime (); } @override public long getLastAccessedTime () {return orgisession.getLastAccessedTime (); } @override public int getMaxInactiveInterval () {return orgisession.getMaxInactiveInterval (); } @override public servletcontext getServletContext () {return orgisession.getServletContext (); } @override public object getValue (String Arg0) {return orgisession.getValue (arg0); } @override public String [] getValuenames () {return orgisession.getValuenames (); } @override public boolean isnew () {return orgisession.isnew (); } @override public void putValue (String Arg0, Object Arg1) {orgisession.putValue (Arg0, Arg1); } @override public void removeValue (String Arg0) {orgisession.removeValue (arg0); } @override public void setmaxinactiveinterval (int arg0) {orgisession.setmaxinactiveinterval (arg0); } @override public httpsessioncontext getsessionContext () {return orgisession.getSessionContext (); }4. 분산 httpservletRequestWrapper는 httpservletrequestwrapper를 구현하고, 처리 된 세션 및 원래 요청, 핵심 코드를 랩핑합니다.
public class distributedhttpservletrequestwrapper 확장 javax.servlet.http.httpervletrequestwrapper {private httpservletrequest orgirequest; Private DistributHtTpsessionWrapper 세션; public distributedhttpservletrequestwrapper (httpservletrequest request, distributedhttpsessionWrapper 세션) {super (request); if (session == null) {// 예외 처리. . } if (request == null) {// 예외 처리. . } this.orgirequest = 요청; this.session = 세션; } public epplicedhttpsessionwrapper getsession (boolean create) {orgirequest.getSession (create); 반환 세션; } public epplicedhttpsessionwrapper getsession () {return session; }}5. 또한 PertipredBaseInterface 인터페이스를 정의하여 지속성 작업을 위해 세션을 Redis로 처리합니다.
public interface distributedbaseinterface { / ** * 키 * @param key * @param seconds * / public string get (문자열 키, int 초)에 따라 캐시 된 데이터 가져 오기; / ** * 캐시 된 데이터 업데이트 * @param key * @param json * @param seconds */ public void set (문자열 키, 문자열 json, int seconds); / *** 캐시 삭제* @param 키*/ public void del (문자열 키); / ** * 만료 된 데이터 설정 * @param key * @param seconds */ public void expire (문자열 키, int 초);참고 :이 기사는 봄에 세션을 관리하기 위해 Redis 메소드 만 사용하며 컨테이너의 구성 등과 같은 다른 구현 방법이 많이 있으며 세션이 무리,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.