이 기사에서는 Redis에 Java 세션을 절약하는 간단한 구현에 대해 설명합니다. 다음과 같이 참조에 대해 공유하십시오.
로드 밸런싱에서 사용자가 다른 컴퓨터에 액세스하고 세션 동기화를 수행하지 않으면 사용자에게 질문을받습니다. 이는 사용자 경험에 매우 좋지 않으므로 세션 동기화를 수행해야합니다. REIDS 캐시 서버에 세션을 넣으면 문제가 해결 될 수 있습니다. 다음은 코드의 간단한 구현입니다.
1. Web.xml 필터 구성 :
<filter> <filter-name> sessionFilter </filter-name> <filter-class> org.spramework.web.filter.delegatingFilterProxy </filter-class> </filter> <filter-mapping> <filter-name> sessionfilter </filter-name> <url-mattern>/*</url-pantn> </filtern>
2. 해당 필터 이름 구성 :
<bean id = "sessionFilter"> <속성 이름 = "redistemplate"ref = "redistemplate"/> </bean>
SessionFilter의 구현 :
공개 클래스 세션 필터는 genericfilterbean {private redistemplate redistemplate; @override public void dofilter (servletrequest 요청, servletresponse 응답, 필터 체인 체인)는 ioexception, servletexception {system.out.println ( "필터"); httpservletrequest re = (httpservletrequest) 요청; httpservletresponse res = (httpservletresponse) 응답; terryhttpservletRequestWrapper 래퍼 = new TerryHtTpservletRequestWrapper (Re, Res, Redistemplate); Chain.dofilter (래퍼, 응답); } public redistemplate getRedistemplate () {return redistemplate; } public void setredistemplate (redistemplate redistemplate) {this.redistemplate = redistemplate; }}4. TerryhttpservletRequestWrapper의 구현 :
공개 클래스 terryhttpservletrequestwrapper는 httpservletrequestwrapper {private cachehttpsession session; 개인 httpservletResponse 응답; 개인 레디 스템 플레이트 레디 스템 플레이트; public terryhttpservletrequestwrapper (httpservletrequest 요청, httpservletreponse 응답, redistemplate redistemplate) {super (request); this.redistemplate = 응답; this.redistemplate = redistemplate; } @override public httpsession getsession (boolean create) {if (session! = null) {return session; } 문자열 sid = "Terry" + System.CurrentTimeMillis (); writesidtocookie (sid); 세션 = 새로운 CACHEHTTPSESSION (NULL, SID, REDISTEMPLATE); 반환 세션; } @override public httpsession getsession () {return getsession (false); } Protected Void writeSidtoCookie (String Sid) {Cookie MyCookies = New Cookie ( "Terry", Sid); MyCookies.SetMaxage (-1); MyCookies.SetDomain ( "locahost"); MyCookies.SetPath ( "/"); 응답 .addcookie (MyCookies); }}5. CACHEHTTPSESSION의 구현 :
공개 클래스 CACHEHTTPSESSION 확장 httpsessionWrapper {private String Sid; 개인 레디 스템 플레이트 레디 스템 플레이트; Private StringRedisserializer stringserializer = new StringRedisserializer (); public cachehttpsession (httpsession session, string sid, redistemplate redistemplate) {super (세션); this.sid = sid; this.redistemplate = redistemplate; } @SuppressWarnings ( "선택 취소") @Override public Enumeration <string> getAttributeNames () {final byte [] key = stringserializer.serialize (sid); Object result = redistemplate.execute (new readiscallback <botort> () {@override public object doinredis (readisconnection connection)는 dataAccessException {set <byte []> set = connection.keys (key); return set;}}); if (result! = null) {set <byte []> s = (set <byte []>) result; <string> ss = new Hashset <문자열> (); for (byte [] b : s) {ss.add (stringserializer.deserialize (b)); } 열거 <string> en = new Vector (ss) .elements (); en; } return null; } @SuppressWarnings ( "선택 취소") @Override public void setAttribute (문자열 이름, 객체 값) {final byte [] key = stringserializer.serialize (이름); 최종 바이트 [] v = stringserializer.serialize ((String) 값); redistemplate.execute (new readiscallback <bood> () {@override public object doinredis (readisconcection connection) dataAccessException {connection.set (key, v); return null;}}); } @override public object getAttribute (문자열 이름) {final byte [] key = stringserializer.serialize (name); @SuppressWarnings ( "확인되지 않은") 객체 값 = redistemplate.execute (new readiscallback <botort> () {@override public object doinredis (retisconnection connection) dataAccessException {return connection.get;}}); 반환 값; } @override public String getId () {return sid; }}6. httpsessionWrapper의 구현 :
공개 클래스 httpsessionWrapper는 httpsession {private httpsession 세션; public httpsessionWrapper (httpsession session) {this.session = session; } @override public long getCreationTime () {return this.session.getCreationTime (); } @override public String getId () {return this.session.getId (); } @override public long getLastAccessedTime () {return this.session.getLastAccessedTime (); } @override public servletcontext getServletContext () {return this.session.getServletContext (); } @override public void setmaxinactiveinterval (int interval) {this.session.setmaxinactiveinterval (Interval); } @override public int getMaxinactiveInterval () {return this.session.getMaxInactiveInterval (); } @override public httpsessioncontext getsessionContext () {return this.session.getSessionContext (); } @override public object getAttribute (String name) {return this.session.getAttribute (name); } @override public object getValue (문자열 이름) {return this.session.getValue (이름); } @override public enumeration <string> getAttributeNames () {return this.session.getAttributeNames (); } @override public String [] getValuenames () {return this.session.getValuenames (); } @override public void stattribute (문자열 이름, 개체 값) {this.session.setattribute (이름, 값); } @override public void putValue (문자열 이름, 객체 값) {this.session.putValue (이름, 값); } @override public void removeattribute (문자열 이름) {this.session.removeattribute (name); } @override public void removeValue (문자열 이름) {this.session.removeValue (이름); } @override public void invalidate () {this.session.invalidate (); } @override public boolean isnew () {return this.session.isnew (); }}위의 코드는 세션을 Redis에 저장할 수 있습니다. 물론 SessionID 생성, 과거 세션, 객체 직렬화 (테스트는 편의를 위해 문자열 사용) 및 기타 많은 문제와 같은 많은 문제가 있습니다. 시간이 있으면 나중에 개선 할 것입니다.
Java 관련 콘텐츠에 대한 자세한 내용은이 사이트의 주제를 확인하십시오 : "Java+MySQL 데이터베이스 프로그래밍 요약", "Java Operation Excel Skills Summary", "Java 데이터 구조 및 알고리즘 자습서", "Java 파일 및 디렉토리 운영 기술 요약"및 "Java Operation Dom Node Skills Summary"
이 기사가 모든 사람의 Java 프로그래밍에 도움이되기를 바랍니다.