SpringBoot+Mybatis項(xiàng)目使用Redis做Mybatis的二級(jí)緩存的方法
介紹
使用mybatis時(shí)可以使用二級(jí)緩存提高查詢速度,進(jìn)而改善用戶體驗(yàn)。
使用redis做mybatis的二級(jí)緩存可是內(nèi)存可控<如將單獨(dú)的服務(wù)器部署出來(lái)用于二級(jí)緩存>,管理方便。
1.在pom.xml文件中引入redis依賴(lài)
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
2.在application.properties配置文件中進(jìn)行redis的配置
## Redis spring.redis.database=0 spring.redis.host=172.16.3.123 spring.redis.port=6379 spring.redis.password= spring.redis.pool.max-active=8 spring.redis.pool.max-wait=-1 spring.redis.pool.max-idle=8 spring.redis.pool.min-idle=0 spring.redis.timeout=0
3.創(chuàng)建cache包,然后創(chuàng)建兩個(gè)類(lèi),一個(gè)ApplicationContextHolder實(shí)現(xiàn)ApplicationContextAware接口,具體內(nèi)容如下
package com.ruijie.SpringBootandRedis.cache; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Component; @Component public class ApplicationContextHolder implements ApplicationContextAware { private static ApplicationContext applicationContext; @Override public void setApplicationContext(ApplicationContext ctx) throws BeansException { applicationContext = ctx; } /** * Get application context from everywhere * * @return */ public static ApplicationContext getApplicationContext() { return applicationContext; } /** * Get bean by class * * @param clazz * @param <T> * @return */ public static <T> T getBean(Class<T> clazz) { return applicationContext.getBean(clazz); } /** * Get bean by class name * * @param name * @param <T> * @return */ public static <T> T getBean(String name) { return (T) applicationContext.getBean(name); } }
4.創(chuàng)建RedisCache類(lèi)實(shí)現(xiàn)Cache接口,具體內(nèi)容如下:
package com.ruijie.SpringBootandRedis.cache; import org.apache.ibatis.cache.Cache; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.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.locks.ReentrantReadWriteLock; public class RedisCache implements Cache { private static final Logger logger = LoggerFactory.getLogger(RedisCache.class); private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock(); private final String id; // cache instance id private RedisTemplate redisTemplate; private static final long EXPIRE_TIME_IN_MINUTES = 30; // redis過(guò)期時(shí)間 public RedisCache(String id) { if (id == null) { throw new IllegalArgumentException("Cache instances require an ID"); } this.id = id; } @Override public String getId() { return id; } /** * Put query result to redis * * @param key * @param value */ @Override public void putObject(Object key, Object value) { try { RedisTemplate redisTemplate = getRedisTemplate(); ValueOperations opsForValue = redisTemplate.opsForValue(); opsForValue.set(key, value, EXPIRE_TIME_IN_MINUTES, TimeUnit.MINUTES); logger.debug("Put query result to redis"); } catch (Throwable t) { logger.error("Redis put failed", t); } } /** * Get cached query result from redis * * @param key * @return */ @Override public Object getObject(Object key) { try { RedisTemplate redisTemplate = getRedisTemplate(); ValueOperations opsForValue = redisTemplate.opsForValue(); logger.debug("Get cached query result from redis"); System.out.println("****"+opsForValue.get(key).toString()); return opsForValue.get(key); } catch (Throwable t) { logger.error("Redis get failed, fail over to db", t); return null; } } /** * Remove cached query result from redis * * @param key * @return */ @Override @SuppressWarnings("unchecked") public Object removeObject(Object key) { try { RedisTemplate redisTemplate = getRedisTemplate(); redisTemplate.delete(key); logger.debug("Remove cached query result from redis"); } catch (Throwable t) { logger.error("Redis remove failed", t); } return null; } /** * Clears this cache instance */ @Override public void clear() { RedisTemplate redisTemplate = getRedisTemplate(); redisTemplate.execute((RedisCallback) connection -> { connection.flushDb(); return null; }); logger.debug("Clear all the cached query result from redis"); } /** * This method is not used * * @return */ @Override public int getSize() { return 0; } @Override public ReadWriteLock getReadWriteLock() { return readWriteLock; } private RedisTemplate getRedisTemplate() { if (redisTemplate == null) { redisTemplate = ApplicationContextHolder.getBean("redisTemplate"); } return redisTemplate; } }
5.實(shí)體類(lèi)中要實(shí)現(xiàn)Serializable接口,并且要聲明序列號(hào)
private static final long serialVersionUID = -2566441764189220519L;
6.開(kāi)啟Mybatis的二級(jí)緩存
在pom.xml配置文件中配置
mybatis.configuration.cache-enabled=true
在mapper接口中加入
@CacheNamespace(implementation=(com.demo.testdemo.cache.RedisCache.class))
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Mybatis調(diào)用存儲(chǔ)過(guò)程的案例
這篇文章主要介紹了Mybatis如何調(diào)用存儲(chǔ)過(guò)程,本文通過(guò)示例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-07-07mybatis逆向工程與分頁(yè)在springboot中的應(yīng)用及遇到坑
最近在項(xiàng)目中應(yīng)用到springboot與mybatis,在進(jìn)行整合過(guò)程中遇到一些坑,在此將其整理出來(lái),分享到腳本之家平臺(tái)供大家參考下2018-09-09Mybatis使用update更新值為null時(shí)不生效問(wèn)題解決
這篇文章主要介紹了Mybatis使用update更新值為null時(shí)不生效問(wèn)題解決,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-06-06MybatisPlus:使用SQL保留字(關(guān)鍵字)的操作
這篇文章主要介紹了MybatisPlus:使用SQL保留字(關(guān)鍵字)的操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-11-11淺談Java代碼的 微信長(zhǎng)鏈轉(zhuǎn)短鏈接口使用 post 請(qǐng)求封裝Json(實(shí)例)
下面小編就為大家?guī)?lái)一篇淺談Java代碼的 微信長(zhǎng)鏈轉(zhuǎn)短鏈接口使用 post 請(qǐng)求封裝Json(實(shí)例)。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-07-07MyBatis?Mapper.XML?標(biāo)簽使用小結(jié)
在MyBatis中,通過(guò)resultMap可以解決字段名和屬性名不一致的問(wèn)題,對(duì)于復(fù)雜的查詢,引用實(shí)體或使用<sql>標(biāo)簽可以定義復(fù)用的SQL片段,提高代碼的可讀性和編碼效率,使用這些高級(jí)映射和動(dòng)態(tài)SQL技巧,可以有效地處理復(fù)雜的數(shù)據(jù)庫(kù)交互場(chǎng)景2024-10-10spring?boot項(xiàng)目中如何使用nacos作為配置中心
這篇文章主要介紹了spring?boot項(xiàng)目中如何使用nacos作為配置中心問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-12-12