SSM+Redis 통합
SSM 프레임 워크는 이전에 구축되었으므로 여기에서 코드 복사가 수행되지 않습니다.
여기서 우리는 주로 Redis를 사용하여 Mybatis의 보조 캐시를 만듭니다. Mybaits 매핑 파일의 모든 선택은 기존 캐시를 새로 고침합니다. 존재하지 않으면 새 캐시가 생성됩니다. 모든 삽입 및 업데이트 작업은 캐시를 업데이트합니다.
Redis의 이점도 분명하므로 시스템의 데이터 액세스 성능을 높일 수 있습니다. 이 섹션에서는 통합 방법과 효과 만 표시되며 나중에 Redis 클러스터,로드 밸런싱 및 세션을 공유하는 기사로 보충됩니다.
통합 작업을 시작하겠습니다.
백엔드는 먼저 시작됩니다 (Linux 서비스에 시작하고 원격으로 연결하는 방법은 redis.conf 파일을 변경해야합니다), 명령을 시작합니다. "./src/redis-server ./redis.conf"
Windows 시스템에서 개발했습니다. 시각적 도구 "Redis Desktop Manager"를 권장합니다. Linux에서 Redis에 원격 연결이 필요하며 Linux 하에서 포트를 대중에게 열어야합니다 (특정 방법은/etc/sysconfig/iptables 파일을 수정하고 외부 포트 개발 명령을 추가하는 것입니다).
위의 모든 작업이 완료되면 그림과 같이 원격 연결이 성공적입니다.
아직 캐시 레코드가 없습니다. 코드 단계에 입력합시다. 먼저 필요한 Redis Jar 패키지를 pom.xml에 추가하십시오.
<pectionency> <groupid> redis.clients </groupid> <artifactid> jedis </artifactid> <bersion> 2.9.0 </version> </fectionency> <pectionency> <groupid> org.springframework.data </groupid> <artifactid> spring-data-redis </arepifactid> <6.2.2.release </version> </version> <6.2. <groupid> org.mybatis </groupid> <artifactid> mybatis-ehcache </artifactid> <버전> 1.0.0 </version> </fectionement> <!-드루이드 연결 풀 패키지 추가-> <pectionency> <groupid> com.alibaba </groupId> <artifactid> druid> <version> 1.0.24 <0.24 <0.24 <0.24
pom.xml이 작성된 후 두 개의 새로운 구성 파일을 추가해야합니다 : redis.properties
redis.host = 192.168.0.109redis.port = 6379redis.pass = 123456redis.maxidle = 200redis.maxactive = 1024redis.maxwait = 100000redis.testonbronge = true
필드도 이해하기 쉽고 구성 파일을 추가합니다 : Spring-Redis.xml
<beans xmlns = "http://www.springframework.org/schema/beans"xmlns : xsi = "http://www.w3.org/2001/xmlschema-instance"xmlns : p = "http://www.spramframframwork.org/pramwerk.org/pramwork.org. xmlns : mvc = "http://www.springframework.org/schema/mvc"xmlns : util = "http://www.springframework.org/schema/util"xmlns : aop = "http://www.spramframwork.org/schema/op. xmlns : context = "http://www.springframework.org/schema/context"xmlns : task = "http://www.springframework.org/schema/task"xsi : schemalocation = "http://www.springframwork.org/schema/schema/schema http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.3.xsd http://www.spramework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd http://www.springframework.org/schema/aop http://www.spramework.org/schema/aop/sprring-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd "> <!-데이터베이스 연결 풀과 유사한 기본 매개 변수 구성 풀의 기본 매개 변수 구성. <bean id = "poolconfig"> <property name = "maxtotal"value = "$ {redis.maxActive}"/> <속성 이름 = "maxIdle"value = "$ {redis.maxidle}"/> <Property name = "testonborry"value = "$ {redis.testonborrow}"-</bean> </bean> </bean> <bean id = "jedisconnectionfactory"> <속성 이름 = "hostname"value = "$ {redis.host}"> </property> <속성 이름 = "port"value = "$ {redis.port}"> </property> <속성 이름 = "valess"valess = "$ {redis.pass}"> </property name> </bean> <!-전화 연결 풀 공장 구성-> <!-<bean id = "redistemplate"> <속성 이름 = "jedisconnectionfactory"ref = "jedisconnectionfactory"> </property> Serializer가 구성되지 않으면 저장시 지능적으로 String을 사용하십시오. 사용자 유형을 사용하여 저장하면 오류 사용자가 문자열로 캐스트 할 수 없습니다! ! ! <property name = "keyserializer"> <bean/> </property> <property name = "valueerializer"> <bean/> </property> </bean> -> <bean id = "readiscaceTransfer"> <property name = "jediscontectionfactory"ref = "jedisconcection factory"/> </beans>구성 파일이 작성된 후 Java 코드 작성을 시작하십시오.
jedisclusterfactory.java
package com.cjl.util; import java.util.hashset; import java.util.properties; import java.util.set; import java.util.regex.pattern; import org.apache.commons.pool2.impl.genericobjectpoolconfig; import org.springfrframework.bean.compory org.springframework.beans.factory.initializingbean; import org.springframework.core.io.resource; import redis.clients.jedis.hostandport; import redis.clients.jedis.jediscluster; public jedisclustory rements factorybean <jedisclust>, 초기화 - {private -bean {jediscluster>; 개인 문자열 addressKeypRefix; 개인 Jediscluster Jediscluster; 개인 정수 타임 아웃; 개인 정수 Maxredirections; 개인 genericobjectpoolconfig genericobjectpoolconfig; 개인 패턴 p = pattern.compile ( "^.+[:] // d {1,5} // s*$"); Public Jediscluster getObject ()는 예외 {return jediscluster; } 공개 클래스 <? jediscluster> getObjecttype () {return (this.jediscluster! = null? this.jediscluster.getClass () : jediscluster.class); } public boolean issingleton () {return true; } private set <hostandport> parsehostandport ()는 예외 {try {properties props = new Properties (); prop.load (this.addressconfig.getInputStream ()); set <hostandport> hasps = new Hashset <Hostandport> (); for (객체 키 : prop.keyset ()) {if (! ((string) key) .startSwith (wasseKeypRefix)) {계속; } 문자열 val = (string) prop.get (키); 부울 isipport = p.matcher (val) .matches (); if (! isipport) {새로운 불법 불법 행위 ( "IP 또는 포트는 불법"); } string [] ipandport = val.split ( ":"); Hostandport hap = New Hostandport (ipandport [0], integer.parseint (ipandport [1]); haps.add (hap); } return hasps; } catch (delegalargumentexception ex) {throw ex; } catch (Exception Ex) {Throw New Exception ( "Parse Jedis 구성 파일 실패", ex); }} public void afterProperTiesset ()는 예외를 던져 {set <hostandport> hasps = this.parsehostandport (); JedisCluster = New Jediscluster (haps, timeout, maxredirections, genericobjectpoolconfig); } public void setAddressconfig (Resource AddressConfig) {this.addressconfig = addressConfig; } public void settimeout (int timeout) {this.timeout = timeout; } public void setMaxRedirection (int maxRedirections) {this.MaxRedirections = maxRedirections; } public void setAddresskeypRefix (String AddressKeypRefix) {this.AddressKeypRefix = addressKeypRefix; } public void setgenericobjectpoolconfig (genericobjectpoolconfig genericobjectpoolconfig) {this.genericobjectpoolconfig = genericobjectpoolconfig; }}readiscache.java
package com.cjl.util; import java.util.concurrent.locks.readwritelock; import java.util.concurrent.locks.reentrantreadwritelock; import org.apache.ibatis.cache.cache; import org.slf4j.logger; import org.slf4j.logger -Actortory; org.springframework.data.redis.connection.jedis.jedisconnection; import org.springframework.data.redis.connection.jedis.jedisconnectionfactory; import org.springframework.data.redis.serialization.jdkserializationrediserializer; import org.springframework.data.redis.serializer.redisserializer; import redis.clients.jedis.exceptions.jedisconnectionexception; public class readiscache emplements cache {private static final logger = loggerfactory.getLogger (readiscache.class); 개인 정적 정적 JedisconnectionFactory JedisconnectionFactory; 개인 최종 문자열 ID; Private Final ReadWritelock RWL = New ReentRantreadWritelock (); public readiscache (최종 문자열 ID) {if (id == null) {새로운 불법 불법 행위 ( "캐시 인스턴스가 ID가 필요"); } logger.debug ( "mybatisrediscache : id =" + id); this.id = id; } / *** 모든 캐시를 지우십시오* / public void clear () {rwl.readlock (). lock (); Jedisconnection Connection = null; try {connection = jedisconnectionfactory.getConnection (); Connection.flushdb (); Connection.flushall (); } catch (jedisconnectionException e) {e.printstacktrace (); } 마침내 {if (connection! = null) {connection.close (); } rwl.readlock (). Unlock (); }} public String getId () {return this.Id; } / *** 총 캐시 수를 가져옵니다* / public int getsize () {int result = 0; Jedisconnection Connection = null; try {connection = jedisconnectionfactory.getConnection (); 결과 = integer.valueof (connection.dbsize (). toString ()); logger.info ( "Mybaits 2 차 캐시 번호 추가 :" + result); } catch (jedisconnectionException e) {e.printstacktrace (); } 마침내 {if (connection! = null) {connection.close (); }} 반환 결과; } public void putobject (객체 키, 객체 값) {rwl.writelock (). lock (); Jedisconnection Connection = null; try {connection = jedisconnectionfactory.getConnection (); Redisserializer <bood> Serializer = New JDKSerializationRedisserializer (); connection.set (serializeutil.serialize (key), serializeutil.serialize (value)); logger.info ( "Mybaits 추가 보조 캐시 키 =" + key + ", value =" + value); } catch (jedisconnectionException e) {e.printstacktrace (); } 마침내 {if (connection! = null) {connection.close (); } rwl.writelock (). unlock (); }} public Object getObject (Object Key) {// 캐시에서 데이터를 먼저 가져옵니다. 읽기 잠금 rwl.readlock (). lock (); 객체 결과 = null; Jedisconnection Connection = null; try {connection = jedisconnectionfactory.getConnection (); Redisserializer <bood> Serializer = New JDKSerializationRedisserializer (); result = serializer.deserialize (connection.get (serializer.serialize (key))); logger.info ( "Mybaits 레벨 2 캐시, value =" + result); } catch (jedisconnectionException e) {e.printstacktrace (); } 마침내 {if (connection! = null) {connection.close (); } rwl.readlock (). Unlock (); } 반환 결과; } public Object RemoveObject (Object Key) {rwl.writelock (). lock (); Jedisconnection Connection = null; 객체 결과 = null; try {connection = jedisconnectionfactory.getConnection (); Redisserializer <bood> Serializer = New JDKSerializationRedisserializer (); result = connection.expire (Serializer.serialize (키), 0); } catch (jedisconnectionException e) {e.printstacktrace (); } 마침내 {if (connection! = null) {connection.close (); } rwl.writelock (). unlock (); } 반환 결과; } public static void setjedisconnectionfactory (jediscontectory jedisconnectionfactory) {readiscache.jedisconnectionfactory = jediscontectionfactory; } public readWritElock getReadWritElock () {// todo 자동 생성 메소드 스터브 리턴 rwl; }}readiscachetransfer.java
packet com.cjl.util; import org.springframework.bean.bean.bean.bean.bean.bean.bean.bean.beans.bean.bean.bean.bean.bean.bean.bean.bean.bean.bean.bean.bean.bean.bean.bean.bean.bean.beans.sprameframework.data.redis.jedis.jedis.jedisconcepransfor의 정적 주입*/public class readiscachetransfer {@autowirecired setistoncired void setistompactor (jediscerector)의 정적 주입 jedisconnectionfactory) {readiscache.setjedisconnectionfactory (jedisconnectionfactory); }}Serializeutil.java
package com.cjl.util; import java.io.bytearrayinputStream; import java.io.bytearrayoutputstream; import java.io.objectinputstream; import java.io.objectoutputstream;/** * * * @author cjl */public serialize {/** serialization */** serialization */** serialization */** ** 객체) {ObjectOutputStream oos = null; BYTEARRAYOUTPUTSTREAM BAOS = NULL; try {// serialization baos = new BytearRayoutputStream (); OOS = 새로운 ObjectOutputStream (BAOS); oos.writeobject (Object); 바이트 [] bytes = baos.tobytearray (); 반환 바이트; } catch (예외 e) {e.printstacktrace (); } return null; } / ***Desserialization* / public static 객체 unserialize (byte [] bytes) {if (bytes! = null) {bytearrayinputStream bais = null; try {// deserialize bais = new bytearrayinputstream (bytes); ObjectInputStream OIS = New ObjectInputStream (BAIS); return ois.readobject (); } catch (예외 e) {}} return null; }}모든 것이 준비되면 매핑 파일을 수정해야합니다.
Mybaits 캐시를 효과적으로 만들려면 위 그림과 같이 보조 캐시를 활성화해야합니다. 구성 파일도 web.xml에로드되어야합니다.
모든 것이 준비되면 서비스를 시작하십시오
시작이 성공한 후 직원 양식을 클릭하면 모든 직원을 쿼리하는 방법이 트리거 될 수 있습니다. 쿼리 명령문이 처음으로 수행되면 Mybatis가 쿼리 문을 인쇄하고 Redis 서버에서 캐시를 업데이트했음을 알 수 있습니다.
콘솔을 지우고 쿼리 직원 버튼을 클릭하여 쿼리 메소드를 실행합니다. 두 번째 쿼리가 캐시에서 직접 값을 가져 오는 것으로 증명하는 쿼리 문이 실행되지 않으며 쿼리를 위해 MySQL과 연결되지 않음을 알 수 있습니다.
요약
위는 편집자가 귀하에게 소개 한 Redis 및 SSM (Mybatis Level 2 캐시)의 통합 방법입니다. 모든 사람에게 도움이되기를 바랍니다. 궁금한 점이 있으면 메시지를 남겨 주시면 편집자가 제 시간에 모든 사람에게 답장을 드리겠습니다. Wulin.com 웹 사이트를 지원해 주셔서 대단히 감사합니다!