소개하다
MyBatis를 사용할 때는 보조 캐시를 사용하여 쿼리 속도를 높이고 사용자 경험을 향상시킬 수 있습니다.
Redis를 사용하여 Mybatis의 보조 캐시를 만들지 만 메모리는 제어 할 수 있습니다. 보조 캐시에 별도의 서버가 배포되면 관리하기 쉽습니다.
1. pom.xml 파일에 Redis 종속성을 소개합니다
<pectionency> <groupId> org.springframework.boot </groupid> <artifactid> 스프링 부트 스타터-데이터-레 디스 </artifactid> </fectionency>
2. Application.Properties 구성 파일에서 redis를 구성합니다
## Redis spring.redis.database = 0spring.redis.host = 172.16.3.123spring.redis.port = 6379Spring.redis.Password = spring.redis.pool.ma x-active = 8spring.redis.pool.max-wait = -1spring.redis.pool.max-idle = 8spring.redis.pool.min-idle = 0spring.redis.timeout = 0
3. 캐시 패키지를 만들고 두 개의 클래스를 만듭니다. 하나의 ApplicationContexTholder는 ApplicationContextAware 인터페이스를 구현합니다. 특정 내용은 다음과 같습니다
패키지 com.ruijie.springbootandredis.cache; import org.springframework.beans.beansexception; import org.springframework.context.applicationcontext; import org.springframework.context.applicationContextAware; import org.springframework.sterepont.component; ApplicationContexTholder는 ApplicationContextAware {private static ApplicationContext ApplicationContext를 구현합니다. @override public void setApplicationContext (ApplicationContext CTX)는 beansexception {ApplicationContext = ctx; } / ** * 모든 곳에서 응용 프로그램 컨텍스트 가져 오기 * * @return * / public static applicationContext getApplicationContext () {return applicationContext; } / ** * 클래스별로 bean get by * @param clazz * @param <t> * @return * / public static <t> t getbean (class <t> clazz) {return applicationcontext.getbean (clazz); } / ** * 클래스 이름으로 Bean을 받기 * * @param name * @param <t> * @return * / public static <t> t getBean (문자열 이름) {return (t) applicationcontext.getBean (이름); }}4. REASISCACHE 클래스를 작성하여 캐시 인터페이스를 구현하려면 특정 컨텐츠는 다음과 같습니다.
package com.ruijie.springbootandredis.cache; import org.apache.ibatis.cache.cache; import org.slf4j.logger; import org.slf4j.loggeractory; import org.spramframework.data.redis.core.rediscallback; import org.springframework.data.redis.core.redistemplate; import org.springframework.data.redis.core.valueoperations; import java.util.concurrent.timeunit; import java.util.concurrent.locks.readwritelock; import java.util.concurrent.concurrant.lortranc REASISCACHE는 캐시 {개인 정적 최종 로거 로거 = loggerFactory.getLogger (readiscache.class); 개인 최종 readWritElock readWritelock = 새로운 ReentrantreadWritelock (); 개인 최종 문자열 ID; // 캐시 인스턴스 ID 개인 redistemplate redistemplate; 개인 정적 최종 최종 Long Expire_time_in_minutes = 30; // redis 만료 시간 public readiscache (string id) {if (id == null) {새로운 불법 불법 행위 렉싱 ( "캐시 인스턴스가 ID 필요"); } this.id = id; } @override public String getId () {return id; } / ** * Query 결과를 redis * * @param key * @param value * / @override public void putobject (개체 키, 개체 값) {try {redistemplate redistemplate = getRedistemplate (); ValueOperations opsforValue = redistemplate.opsforValue (); opsforvalue.set (키, 값, expire_time_in_minutes, timeUnit.minutes); logger.debug ( "쿼리 결과를 redis에 넣음"); } catch (Throwable t) {logger.error ( "Redis Put 실패", t); }} / ** * redis * * @param key * @return * / @override public object getObject (Object Key) {try {redistemplate redistemplate = getRedistemplate (); ValueOperations opsforValue = redistemplate.opsforValue (); logger.debug ( "redis에서 캐시 된 쿼리 결과를 얻습니다"); System.out.println ( "****"+opsforvalue.get (key) .toString ()); return opsforvalue.get (key); } catch (Throwable t) {logger.error ( "redis가 실패하고 db에 실패", t); 널 리턴; }} / ** * redis * * @param key * @return * / @override @suppresswarnings ( "확인되지 않은") 공개 객체 removeObject (Object Key) {try {redistemplate redistemplate = getRedistemplate (); redistemplate.delete (키); logger.debug ( "Redis에서 캐시 된 쿼리 결과 제거"); } catch (Throwable t) {logger.error ( "Redis 제거 실패", t); } return null; } / ** *이 캐시 인스턴스를 지우는 경우 * / @override public void clear () {redistemplate redistemplate = getRedistemplate (); redistemplate.execute ((readiscallback) connection-> {connection.flushdb (); return null;}); logger.debug ( "Redis의 모든 캐시 된 쿼리 결과를 지우기"); } / ** *이 메소드는 사용되지 않습니다 * * @return * / @override public getsize () {return 0; } @override public readwritelock getReadWritElock () {return readWritElock; } private redistemplate getRedistemplate () {if (redistemplate == null) {redistemplate = ApplicationContexTholder.getBean ( "redistemplate"); } reture redistemplate를 반환합니다. }}5. 직렬화 가능한 인터페이스는 엔티티 클래스에서 구현해야하며 시퀀스 번호를 선언해야합니다.
개인 정적 최종 최종 긴 SerialversionUID = -2566441764189220519L;
6. Mybatis 레벨 2 캐시를 켜십시오
pom.xml 구성 파일로 구성하십시오
mybatis.configuration.cache-enabled = true
맵퍼 인터페이스에 추가하십시오
@Cachenamespace (구현 = (com.demo.testdemo.cache.rediscache.class)))
위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.